vue中mixins的理解及應用


vue中mixins的理解及應用

vue中提供了一種混合機制--mixins,用來更高效的實現組件內容的復用。最開始我一度認為這個和組件好像沒啥區別。。后來發現錯了。下面我們來看看mixins和普通情況下引入組件有什么區別?

mixins

混合 (mixins) 是一種分發 Vue 組件中可復用功能的非常靈活的方式。
混合對象可以包含任意組件選項。
當組件使用混合對象時,所有混合對象的選項將被混入該組件本身的選項。

mixins理解

組件在引用之后相當於在父組件內開辟了一塊單獨的空間,來根據父組件props過來的值進行相應的操作,單本質上兩者還是涇渭分明,相對獨立。

而mixins則是在引入組件之后,則是將組件內部的內容如data等方法、method等屬性與父組件相應內容進行合並。相當於在引入后,父組件的各種屬性方法都被擴充了。

  • 單純組件引用:
    父組件 + 子組件 >>> 父組件 + 子組件
  • mixins:
    父組件 + 子組件 >>> new父組件
    有點像注冊了一個vue的公共方法,可以綁定在多個組件或者多個Vue對象實例中使用。另一點,類似於在原型對象中注冊方法,實例對象即組件或者Vue實例對象中,仍然可以定義相同函數名的方法進行覆蓋,有點像子類和父類的感覺。

mixins的使用

方法的復用

html

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

js

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:{
        foo(){
            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中的。

方法的覆蓋

如果在引用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"

合並生命周期

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)
        }
    }
})

通過上面的介紹,現在對mixins有了比較深入的了解,在設計復雜組件時是很有必要的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM