这一节了解一下Vue3中的mixin,混入(mixin)是Vue3选项式API中用于组件逻辑复用的机制,本质是一个包含任意组件选项的普通对象,通过 mixins 数组合并到组件中,总结如下:
API:
mixin:一个普通JS对象,可以包含组件选项(data、methods、created、computed等)。把多个组件重复的选项抽离成mixin对象,组件引入后合并到组件自身选项。
场景:
1 表单校验
2 页面加载loading等等
栗子:
TypeScript
<!-- DemoMixLoading.vue -->
<template>
<div>
<div v-if="isLoading">加载中...</div>
<div v-if="dataText">{{ dataText }}</div>
<button @click="fetchData">发起请求</button>
</div>
</template>
<script>
const loadingMixin = {
data() {
return {
isLoading: false,
dataText: ""
};
},
methods: {
async fetchData() {
this.isLoading = true;
await new Promise(resolve => setTimeout(resolve, 1500));
this.dataText = "接口返回的数据";
this.isLoading = false;
}
},
created() {
console.log("mixin created 执行");
}
};
export default {
mixins: [loadingMixin],
data() {
return {};
},
created() {
console.log("组件本身 created 执行");
}
}
</script>
TypeScript
<!-- Demo02Mixin.vue -->
<template>
<div>
<p>计数:{{ count }}</p>
<p>双倍计数:{{ doubleCount }}</p>
<p>当前时间:{{ formatNowTime }}</p>
<button @click="addCount">+1</button>
<button @click="resetCount">重置</button>
</div>
</template>
<script>
const countMixin = {
data() {
return {
count: 0
};
},
computed: {
doubleCount() {
return this.count * 2;
}
},
methods: {
addCount() {
this.count++;
},
resetCount() {
this.count = 0;
}
},
watch: {
count(newVal) {
console.log("mixin监听到count变化:", newVal);
}
},
created() {
console.log("countMixin created");
}
};
const timeMixin = {
data() {
return {
now: new Date()
};
},
computed: {
formatNowTime() {
return new Date(this.now).toLocaleString();
}
},
created() {
this.timer = setInterval(() => {
this.now = new Date();
}, 1000);
console.log("timeMixin created");
},
unmounted() {
clearInterval(this.timer);
console.log("timeMixin unmounted,清除定时器");
}
};
export default {
mixins: [countMixin, timeMixin],
methods: {
resetCount() {
this.count = 10;
console.log("组件自己的resetCount执行");
}
},
created() {
console.log("组件本身 created");
},
unmounted() {
console.log("组件unmounted");
}
}
</script>
注意:
1.命名冲突风险:mixin 和组件如果有同名data/methods,组件直接覆盖,无报错,容易隐藏bug。
2.隐式依赖:组件不知道mixin里面有什么属性,可读性差,不好追踪变量来源。
3.多mixin叠加:引入多个mixin时,变量来源难以定位。
4.组合式API setup中,mixin对setup里的变量无效,只能作用于选项。