VUE3 之 使用 Mixin 實現代碼的復用 - 這個系列的教程通俗易懂,適合新手


1. 概述

老話說的好:舍得舍得,先舍才能后得。

 

言歸正傳,今天我們來聊聊 VUE 中使用 Mixin 實現代碼的復用。

 

2. Mixin 的使用

2.1 不使用 Mixin 的寫法

<body>
    <div id="myDiv"></div>
</body>
<script>
    const app = Vue.createApp({
        data(){
            return {
                num : 1
            }
        },

        created() {
            console.info('created');
        },

        methods : {
            myAdd() {
                console.info('myAdd');
            }
        },

        template:`
            <div>
                <button @click="myAdd">增加</button>
                <div>{{num}}</div>
            </div>
        `
    });
    const vm = app.mount("#myDiv");

 

 

 這個例子中,我們使用了之前聊過的 data、生命周期函數 created,method

 

2.2 在 Mixin 中定義 data

   const myMixin = {
        data(){
            return {
                num : 2,
                count : 1
            }
        }
    }

    const app = Vue.createApp({
        data(){
            return {
                num : 1
            }
        },
        created() {
            console.info('created');
        },
        mixins:[myMixin],    
        methods : {
            myAdd() {
                console.info('myAdd');
            }
        },
        template:`
            <div>
                <button @click="myAdd">增加</button>
                <div>{{num}}</div>
                <div>{{count}}</div>
            </div>
        `
    });

 

這個例子中,我們在 Mixin 中定義了 data,並在主組件中使用 mixins:[myMixin] 引用了 Mixin。

並且我們得到了一個結論,組件中的 data 變量比 Mixin 中 data 變量的優先級高,因此 num 最終是 1,而不是 2。

 

2.3 在 Mixin 中定義生命周期函數

    const myMixin = {
        data(){
            return {
                num : 2,
                count : 1
            }
        },
        created() {
            console.info('myMixin created');
        },

    }

 

兩個生命周期函數都會執行,Mixin 的先執行,組件中的后執行

 

2.4 在 Mixin 中定義 method

    const myMixin = {
        data(){
            return {
                num : 2,
                count : 1
            }
        },
        created() {
            console.info('myMixin created');
        },
        methods : {
            myAdd() {
                console.info('myMixin myAdd');
            }
        },
    }

 

 組件中 method 的會覆蓋 mixin中的同名 method

 

2.5 子組件中使用 Mixin

    app.component('sub-com', {
        mixins:[myMixin], 
        template: `
            <div>{{count}}</div>
        `
    });

 

        template:`
            <div>
                <button @click="myAdd">增加</button>
                <div>{{num}}</div>
                <sub-com />
            </div>
        `

子組件中使用 Mixin,需要在子組件中使用 mixins:[myMixin] 引用 Mixin,只在主組件中引用 Mixin 是不行的,主組件、子組件都需要引用 Mixin。

 

3. 綜述

今天聊了一下 VUE3 中使用 Mixin 實現代碼的復用,希望可以對大家的工作有所幫助,下一節我們繼續講 Vue 中的高級語法,敬請期待

歡迎幫忙點贊、評論、轉發、加關注 :)

關注追風人聊Java,這里干貨滿滿,都是實戰類技術文章,通俗易懂,輕松上手。

 

4. 個人公眾號

追風人聊Java,歡迎大家關注


免責聲明!

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



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