咱們先來看官網怎么說~~~
混入 (mixin) 提供了一種非常靈活的方式,來分發 Vue 組件中的可復用功能。一個混入對象可以包含任意組件選項。當組件使用混入對象時,所有混入對象的選項將被“混合”進入該組件本身的選項。
即 mixin 在引入組件之后,會將組件內部的內容如data、method等屬性與父組件相應內容進行合並。相當於在引入后,父組件的各種屬性方法都被擴充了。
let mixin = { data () { return { userName: 'mixin' } }, created () { this.sayHello() }, methods: { sayHello () { console.log(`${this.userName}, welcome`) } } } export default mixin
然后定義兩個組件,分別在組件中引入:
<script> import mixin from '../mixin' export default { mixins: [mixin] } </script>
則兩個組件的打印結果都為:
如果在兩個組件 data 中定義了各自的 userName,則打印結果會引用各自組件中的 userName
如果在兩個組件的 methods 中重復定義了相同的方法,則 mixin 中的方法會被覆蓋
給其中一個組件定義自己的 userName 和 sayHi 方法:
<script> import mixin from '../mixin' export default { mixins: [mixin], data() { return { userName: 'BComponent' } }, created () { this.sayHello() }, methods: { sayHello () { console.log(`Hi, ${this.userName}`) } } } </script>
則打印結果:
這有點像注冊了一個 vue 公共方法,可以在多個組件中使用。還有一點類似於在原型對象中注冊方法,並且可以定義相同函數名的方法進行覆蓋
我一般在項目中會這樣用,比如在多個組件中有用到通用選擇器,選項是:是,否,可以使用 mixin 來添加一個統一的字典項過濾器,來實現選項的回顯。
1. 首先創建一個 Dictionary.js 文件,用於保存字典項對應的含義,並將其暴露出去:
export const COMMON_SELECT = [ { code: 0, label: '是'}, { code: 1, label: '否'} ];
注:此處創建的 Dictionary.js 文件,也可以在頁面渲染的時候拿來循環選項,具體代碼如下:

import { COMMON_SELECT } from '../constants/Dictionary.js' export default { data() { return { comSelectOptions: COMMON_SELECT } } } <select v-mode="selStatus"> <el-option v-for="item in comSelectOptions" :key="item.code" :label="item.label" :value="item.code"></el-option> </select>
2. 然后再創建一個 filter.js 文件,保存自定義的過濾函數:
import { COMMON_SELECT } from '../constants/Dictionary.js' export default { filters: { comSelectFilter: (value) => { const target = COMMON_SELECT.filter(item => { return item.code === value }) return target.length ? target[0].label : value } } }
3. 最后在 main.js 中一次性引入 filter 方法:
import filter from './mixin/filter'
Vue.mixin(filter)
歐了,這樣我們就可以在任一組件中隨意使用了
<template> <div> .... {{ status | comSelectFilter }} .... </div> </template>