vue的mixins的使用


mixins就是混入。

一個混入對象可以包含任意組件選項。

同一個生命周期,混入對象會比組件的先執行。

1.創建一個test.js,用export暴露出mixins對象

export const mixinsTest = {
    methods:{
        hello(){
            console.log("hello");
            
        }
    },
    created(){
        this.hello()
    }
}

2.在組件中引入這個mixins對象,通過mixins:[xxx],使用mixins對象

<template>
<div>
    home
</div>
</template>
<script>
import {mixinsTest} from '../util/test.js'
export default {
  name: "Home",
  data () {
    return {
    };
  },
  created(){
      console.log("home");
      
  },
  //mixins的created會先被調用,然后再執行組件的created
  mixins:[mixinsTest]
}
</script>

 

補充:

可以混入多個mixins對象

//暴露兩個mixins對象
export const mixinsTest = {
    methods: {
        hello() {
            console.log("hello mixins");
        }
    },
    created() {
        this.hello();
    },
}


export const mixinsTest2 = {
    methods:{
        hello2(){
            console.log("hello2");
        }
    },
    created() {
        this.hello2();
    },
}

組件中引入兩個mixins對象

<template>
<div>
    home
</div>
</template>
<script>
import {mixinsTest,mixinsTest2} from '../util/test.js'
export default {
  name: "Home",
  data () {
    return {
    };
  },
  created(){
      console.log("1212");
  },
  mixins:[mixinsTest2,mixinsTest] // 先調用那個mixins對象,就先執行哪個
 
}
</script>
<style lang="css" scoped>
</style>

打印的順序是:

 


免責聲明!

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



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