Vue.js學習(三):mixins混合對象的使用

我對mixins的理解是,有點像註冊了一個vue的公共方法,可以綁定在多個組件或者多個Vue對象實例中使用。另一點,類似於在原型對象中註冊方法,實例對象即組件或者Vue實例對象中,仍然可以定義相同函數名的方法進行覆蓋,有點像子類和父類的感覺。下面主要參考網上的一些資料,對mixins的實際作用做介紹:


1、方法的複用

<div id="app">
    <child></child>
    <kid></kid>
</div>

Vue.component('child',{
    template:`<h1 @click="foo">child component</h1>`,
    methods:{
        foo(){
            console.log('Child foo()'+this.msg++)
        }
    }
})

Vue.component('kid',{
    template:`<h1 @click="foo">kid component</h1>`,
    methods:{
        foo(){
            console.log('Kid foo()'+this.msg++)
        }
    }
})

在藉助mixins之前,在兩個不同的組件的組件中調用foo方法,需要重複定義,倘若方法比較複雜,代碼將更加冗餘。若藉助mixins,則變得十分簡單:

let mixin={
    data(){
        return{
            msg:1
        }
    },
    methods:{
        hello(){
            console.log('hello from mixin!----'+this.msg++)
        }
    }
}
var child=Vue.component('child',{ 
        template:`<h1 @click="foo">child component</h1>`, 
        mixins:[mixin]
})
Vue.component('kid',{ 
        template:`<h1 @click="foo">kid component</h1>`, 
        mixins:[mixin]
})

雖然此處,兩個組件用可以通過this.msg引用mixins中定義的msg,但是,小編嘗試過,兩個組件引用的並不是同一個msg,而是各自創建了一個新的msg。如果在組件中定義相同的data,則此處會引用組件中的msg,而非mixins中的。


2、方法的覆蓋  

如果在引用mixins的同時,在組件中重複定義相同的方法,則mixins中的方法會被覆蓋。

var child=Vue.component('child',{
    template:`<h1 @click="foo">child component</h1>`,
    mixins:[mixin],
    methods:{
        foo(){
            console.log('Child foo()'+this.msg++)
        }
    }
})
此時,若單擊h1標籤,則在控制檯中打印"Child foo() 1" 3、合併生命週期此時,若單擊h1標籤,則在控制檯中打印"Child foo() 1" 


3、合併生命週期

let mixin={
    mounted(){
        console.log('mixin say hi')//先輸出
    },
    data(){
        return{
            msg:1
        }
    },
    methods:{
        foo(){
            console.log('mixin foo()'+this.msg++)
        }
    }
}
let vm=new Vue({
    el:"#app",
    data:{
        msg: 2
    },
    mounted: function(){
        console.log('app say hi')//後輸出
    },
    methods:{
        foo(){
            console.log('Parent foo()'+this.msg)
        }
    }
})

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章