混入 (mixin) 提供了一種很是靈活的方式,來分發 Vue 組件中的可複用功能。一個混入對象能夠 包含任意組件選項。當組件使用混入對象時,全部混入對象的選項將被 「混合」進入該組件自己的選項。
戳 我 查 看 官 方 文 檔
即 mixin 在引入組件以後,是將組件內部的內容如data、method等屬性與父組件相應內容進行合併。至關於在引入後,父組件的各類屬性方法都被擴充了。html
好比在兩個不一樣的組件的組件中調用sayHi方法,須要重複定義,假若方法比較複雜,代碼將更加冗餘。若藉助mixins,則變得十分簡單:vue
首先在 mixin.js 文件中定義一個混入對象:ide
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>
則兩個組件的打印結果都爲:ui
若是在兩個組件 data 中定義了本身的 userName,則打印結果會引用各自組件中的 userNamethis
若是在兩個組件methods 中重複定義了相同的方法,則 mixin 中的方法會被覆蓋spa
給其中一個組件定義本身的 userName 和 sayHi 方法::code
<script\> import mixin from '../mixin' export default { mixins: \[mixin\], data() { return { userName: 'BComponent' } }, created () { this.sayHello() }, methods: { sayHello () { console.log(\`Hi, ${this.userName}\`) } } } </script>
則打印結果爲:htm
這有點像註冊了一個 vue 公共方法,能夠在多個組件中使用。還有一點相似於在原型對象中註冊方法,而且能夠定義相同函數名的方法進行覆蓋。對象
混入也能夠進行全局註冊,但通常狀況下不會全局使用,由於會污染 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>
這個相似於過濾,你們也能夠 點此查看過濾器的使用方法