中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

Vue.js 混入

混入 (mixins)定義了一部分可復(fù)用的方法或者計算屬性?;烊雽ο罂梢园我饨M件選項(xiàng)。當(dāng)組件使用混入對象時,所有混入對象的選項(xiàng)將被混入該組件本身的選項(xiàng)。

來看一個簡單的實(shí)例:

實(shí)例

var vm = new Vue({ el: '#databinding', data: { }, methods : { }, }); // 定義一個混入對象 var myMixin = { created: function () { this.startmixin() }, methods: { startmixin: function () { document.write("歡迎來到混入實(shí)例"); } } }; var Component = Vue.extend({ mixins: [myMixin] }) var component = new Component();

運(yùn)行代碼 ?

選項(xiàng)合并

當(dāng)組件和混入對象含有同名選項(xiàng)時,這些選項(xiàng)將以恰當(dāng)?shù)姆绞交旌稀?/p>

比如,數(shù)據(jù)對象在內(nèi)部會進(jìn)行淺合并 (一層屬性深度),在和組件的數(shù)據(jù)發(fā)生沖突時以組件數(shù)據(jù)優(yōu)先。

以下實(shí)例中,Vue 實(shí)例與混入對象包含了相同的方法。從輸出結(jié)果可以看出兩個選項(xiàng)合并了。

實(shí)例

var mixin = { created: function () { document.write('混入調(diào)用' + '<br>') } } new Vue({ mixins: [mixin], created: function () { document.write('組件調(diào)用' + '<br>') } });

輸出結(jié)果為:

混入調(diào)用
組件調(diào)用

運(yùn)行代碼 ?

如果 methods 選項(xiàng)中有相同的函數(shù)名,則 Vue 實(shí)例優(yōu)先級會較高。如下實(shí)例,Vue 實(shí)例與混入對象的 methods 選項(xiàng)都包含了相同的函數(shù):

實(shí)例

var mixin = { methods: { hellworld: function () { document.write('HelloWorld 方法' + '<br>'); }, samemethod: function () { document.write('Mixin:相同方法名' + '<br>'); } } }; var vm = new Vue({ mixins: [mixin], methods: { start: function () { document.write('start 方法' + '<br>'); }, samemethod: function () { document.write('Main:相同方法名' + '<br>'); } } }); vm.hellworld(); vm.start(); vm.samemethod();

輸出結(jié)果為:

HelloWorld 方法
start 方法
Main:相同方法名

運(yùn)行代碼 ?

以上實(shí)例,我們調(diào)用了以下三個方法:

vm.hellworld();
vm.start();
vm.samemethod();

從輸出結(jié)果 methods 選項(xiàng)中如果碰到相同的函數(shù)名則 Vue 實(shí)例有更高的優(yōu)先級會執(zhí)行輸出。


全局混入

也可以全局注冊混入對象。注意使用! 一旦使用全局混入對象,將會影響到 所有 之后創(chuàng)建的 Vue 實(shí)例。使用恰當(dāng)時,可以為自定義對象注入處理邏輯。

實(shí)例

// 為自定義的選項(xiàng) 'myOption' 注入一個處理器。 Vue.mixin({ created: function () { var myOption = this.$options.myOption if (myOption) { console.log(myOption) } } }) new Vue({ myOption: 'hello!' }) // => "hello!"

運(yùn)行代碼 ?

謹(jǐn)慎使用全局混入對象,因?yàn)闀绊懙矫總€單獨(dú)創(chuàng)建的 Vue 實(shí)例 (包括第三方模板)。