1. 概述
老话说的好:舍得舍得,先舍才能后得。
言归正传,今天我们来聊聊 VUE 中使用 Mixin 实现代码的复用。
2. Mixin 的使用
2.1 不使用 Mixin 的写法
<body><divid="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,这里干货满满,都是实战类技术文章,通俗易懂,轻松上手。