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>

复制代码; "复制代码")

打印的顺序是:


Original url: Access
Created at: 2020-02-15 18:02:41
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论