深入了解Vue.js 混入(mixins)
混入 (mixins)定義了一部分可復(fù)用的方法或者計(jì)算屬性。混入對象可以包含任意組件選項(xiàng)。當(dāng)組件使用混入對象時(shí),所有混入對象的選項(xiàng)將被混入該組件本身的選項(xiàng)。
來看一個(gè)簡單的實(shí)例:
var vm = new Vue({ el: ’#databinding’, data: { }, methods : { },});// 定義一個(gè)混入對象var myMixin = { created: function () { this.startmixin() }, methods: { startmixin: function () { document.write('歡迎來到混入實(shí)例'); } }};var Component = Vue.extend({ mixins: [myMixin]})var component = new Component();
選項(xiàng)合并
當(dāng)組件和混入對象含有同名選項(xiàng)時(shí),這些選項(xiàng)將以恰當(dāng)?shù)姆绞交旌稀?/p>
比如,數(shù)據(jù)對象在內(nèi)部會(huì)進(jìn)行淺合并 (一層屬性深度),在和組件的數(shù)據(jù)發(fā)生沖突時(shí)以組件數(shù)據(jù)優(yōu)先。
以下實(shí)例中,Vue 實(shí)例與混入對象包含了相同的方法。從輸出結(jié)果可以看出兩個(gè)選項(xiàng)合并了。
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)用
如果 methods 選項(xiàng)中有相同的函數(shù)名,則 Vue 實(shí)例優(yōu)先級會(huì)較高。如下實(shí)例,Vue 實(shí)例與混入對象的 methods 選項(xiàng)都包含了相同的函數(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:相同方法名
以上實(shí)例,我們調(diào)用了以下三個(gè)方法:
vm.hellworld();vm.start();vm.samemethod();
從輸出結(jié)果 methods 選項(xiàng)中如果碰到相同的函數(shù)名則 Vue 實(shí)例有更高的優(yōu)先級會(huì)執(zhí)行輸出。
全局混入
也可以全局注冊混入對象。注意使用! 一旦使用全局混入對象,將會(huì)影響到 所有 之后創(chuàng)建的 Vue 實(shí)例。使用恰當(dāng)時(shí),可以為自定義對象注入處理邏輯。
// 為自定義的選項(xiàng) ’myOption’ 注入一個(gè)處理器。Vue.mixin({ created: function () { var myOption = this.$options.myOption if (myOption) { console.log(myOption) } }}) new Vue({ myOption: ’hello!’})// => 'hello!'
謹(jǐn)慎使用全局混入對象,因?yàn)闀?huì)影響到每個(gè)單獨(dú)創(chuàng)建的 Vue 實(shí)例 (包括第三方模板)。
以上就是深入了解Vue.js 混入的詳細(xì)內(nèi)容,更多關(guān)于Vue.js 混入的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python中Anaconda3 安裝gdal庫的方法2. PHP AOP教程案例3. python用zip壓縮與解壓縮4. python公司內(nèi)項(xiàng)目對接釘釘審批流程的實(shí)現(xiàn)5. Notepad++如何配置python?配置python操作流程詳解6. Python 簡介7. Python操作Excel工作簿的示例代碼(*.xlsx)8. JAVA如何轉(zhuǎn)換樹結(jié)構(gòu)數(shù)據(jù)代碼實(shí)例9. Python importlib模塊重載使用方法詳解10. Python自動(dòng)化之定位方法大殺器xpath
