VUE--mixins的一些理解。


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

用法:

  1、創建混入對象:在src文件夾創建mixins文件夾,再在mixins文件夾下創建一個index.js文件

// 創建一個需要混入的對象 
export const mixinstest = {
    data(){
        return {
            testMix: '混入對象的data'
        }
    },
    created(){
        console.log('這是混入對象的created')
    },
    methods:{
        mixinsFun(){
            console.log('調用混入對象的methods的函數')
        }
    },
    computed:{
        testMix2(){
            return this.testMix+':這是混入對象計算結果。'
        }
    },
    watch: {
        testMix(newVal,oldVal){
            console.log('混入對象的watch')
        }
    }
}

  2、在組件內引入並引用混入

<template>
    <div>
        <div>{{testMix}}</div>
        <div @click="mixinsFun">{{testMix}}</div>
        <input type="text" v-model="testMix">
        <div>{{testMix2}}</div>
    </div>
</template>
<script>
import {mixinstest} from '../../mixins/index' 
export default {
    mixins: [mixinstest],
    data (){
        return {
            testMix:'這是組件的數據'
        }
    },
    created(){
        console.log('這是組件的created')
    },
    methods: {
        mixinsFun(){
            console.log('調用組件的methods的函數')
        }
    },
    computed:{
        testMix2(){
            return this.testMix+':這是組件計算結果'
        }
    },
    watch: {
        testMix(newVal,oldVal){
            console.log('組件的watch')
        }
    }
}
</script>
<style>

</style>

  3、相關的解釋

  3.1 當在組件中和混入中有相同的‘testMix’這個數據時,顯示組件中’testMix’對應的數據,當只用混入中有’testMix‘函數時,顯示混入中’testMix’對應的數據。

  3.2 在組件中和混入中有相同的函數mixinsFun()時,在組件中調用時,調用的是組件中的mixinsFun()函數,當只用混入中有mixinsFun()函數時,在組件中調用mixinsFun()是調用混入中的。
  3.3 在組件中和混入中有相同的computed函數testMix2()時,在組件中調用時,調用的是組件中的testMix2()函數,當只用混入中有computed函數testMix2()時,在組件中調用testMix2()是調用混入中的。

  3.4在組件中和混入中有相同的created()函數時,先執行混入中的created,再執行組件中的created。猜想其他生命周期也應該是一樣。

  3.5在組件中和混入中有相同的watch()函數testMix時,先執行混入中watch的testMix,再執行組件中watch的testMix。

  

 


免責聲明!

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



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