Vue組件公用方法提取mixin實現(xiàn)
更新時間:2022年03月29日 11:41:38 作者:什么都干的派森
這篇文章主要介紹了Vue組件公用方法提取mixin實現(xiàn),多個組件共用一個方法時可以用?mixin?抽取到一個js文件中,作為共用方法,下面一起進(jìn)入文章了解更多詳細(xì)內(nèi)容吧
一.應(yīng)用場景
多個組件共用一個方法時可以用 mixin 抽取到一個js文件中,作為共用方法
二.實現(xiàn)方法
1.提取js共用方法文件

export const common = {
?? ?
?? ?// 組件共用屬性 ----------------------------------
?? ?data() {
?? ??? ?return {
?? ??? ??? ?age: 18?? ??? ??? ? ? ? ? ?// 設(shè)置一個共用屬性
?? ??? ?}
?? ?},
?? ?// ---------------------------------------------
?? ?
?? ?// 組件共用方法 ---------------------------------------------
?? ?methods: {
?? ??? ?showName() {
?? ??? ??? ?alert(this.name) ??? ??? ?// 彈出組件中name屬性的共用方法
?? ??? ?}
?? ?},
?? ?// --------------------------------------------------------
?? ?
?? ?// 組件掛載時的共用方法 ----------------------
?? ?mounted() {
?? ??? ?console.log('初始化方法') ? ?// 掛載時調(diào)用
?? ?},
?? ?// ----------------------------------------
?? ?
}2.引入
<template>
?? ?<div>
?? ??? ?<div>組件</div>
?? ??? ?<button @click="showName">彈出姓名</button>
?? ?</div>
</template>
<script>
?? ?// 引入js文件中的方法對象 --------------------
?? ?import {common, } from '../pub_js/common.js'
?? ?// ----------------------------------------
?? ?
?? ?export default {
?? ??? ?name: 'Student',
?? ??? ?data() {
?? ??? ??? ?return {
?? ??? ??? ??? ?name: '張三'
?? ??? ??? ?}
?? ??? ?},
?? ??? ?
?? ??? ?// 調(diào)用 mixin 將組件js與共用js合并 ---
?? ??? ?mixins: [common, ],
?? ??? ?// --------------------------------
?? ??? ?
?? ?}
</script>三.注意事項
- 1.
data中的屬性合并后,如果有命名沖突的情況,以組件中的屬性為主,【組件屬性覆蓋共用js中的屬性】 - 2.
methods中的方法合并后,如果有命名沖突的情況,以組件中的方法為主,【組件方法覆蓋共用js中的方法】 - 3.
mounted等生命周期方法合并后,會先調(diào)用共用js中的的生命周期函數(shù),再調(diào)用組件中的生命周期函數(shù),【不會進(jìn)行覆蓋】 - 4.如果是全局共用的方法,可以直掛載到main.js中↓
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// 掛載全局共用方法 -----------------------
import {common, } from 'pub_js/common.js'
Vue.mixin(common)
// --------------------------------------
new Vue({
? render: h => h(App),
}).$mount('#app')到此這篇關(guān)于Vue組件公用方法提取mixin實現(xiàn)的文章就介紹到這了,更多相關(guān)Vue組件提取內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

