混入 (mixin) 提供了一種非常靈活的方式,來分發 Vue 組件中的可復用功能。一個混入對象可以包含任意組件選項。當組件使用混入對象時,所有混入對象的選項將被“混合”進入該組件本身的選項。
使用示例:
需求:
假設我 demoA組件和demoB組件中有相同的一些方法和處理邏輯。這時候我們為了不寫重復的代碼,可以視情況使用 混入mixins.
演示目錄:
在mixins.js里定義了混入對象 並通過export導出:
// 定義一個混入對象:(這里是局部混入,全局混入官網詳見:https://cn.vuejs.org/v2/guide/mixins.html) //具體混入對象和組件直接的使用詳見: https://cn.vuejs.org/v2/guide/mixins.html //在demoA.vue 和 demeB.vue混入以后,兩個組件里就都擁有了, hello方法,並自動在created中執行 export var myMixin = { //組件中的其他屬性 都可寫在這里 methods: { hello: function (msg='') { console.log('hello from mixin!' + msg); } }, created: function () { this.hello(); // 同名鈎子函數將合並為一個數組,因此都將被調用。另外,混入對象的鈎子將在組件自身鈎子之前調用。 console.log('混入對象-created'); } };
在demoA組件和demoB組件中使用 mininx 混入。
demoA.vue
<template> <div class="demoA"> demoA </div> </template> <script> import { myMixin } from './mixins/mixins'; export default { name: 'demoA', mixins: [ myMixin ], //混入 相當把 混入對象的 屬性 都 寫在了當前 組件里。 data(){ return { } }, methods: { bar: function () { console.log('demoA-methods-bar'); } }, created(){ this.bar(); }, mounted () { console.log('demoA-mounted'); // this.hello(demoA); //調用混入對象中methods中的方法 -> hello from mixin!demoA } }; </script> <style scoped> </style>
demoB.vue
<template> <div class="demoB"> demoB </div> </template> <script> import { myMixin } from './mixins/mixins'; export default { name: 'demoB', mixins: [ myMixin ], //混入 相當把 混入對象的 屬性 都 寫在了當前 組件里。 data(){ return { foo: 'foo' } }, methods: { }, created(){ console.log('demoB-created') }, mounted () { console.log('demoB-mounted'); // this.hello('demoB'); //調用混入對象中methods中的方法 -> hello from mixin!demoB } }; </script> <style scoped> </style>
簡單運行效果:
具體使用方式:詳見官網api:https://cn.vuejs.org/v2/guide/mixins.html