Mixins 是 Vue.js 提供的,用于代码复用的非常有用的特性,尤其是针对函数的复用。Mixins 是混合的意思,Vue 实例引用 mixins 文件,mixins 对象中的公共方法会合并到 Vue 实例中被复用。
以下是完整的 mixins 使用示例,请按照以下列举的规则使用 mixins。
示例
// toggleMixin.js
const toggleMixin = {
data() {
return {
isShowing: false
}
},
methods: {
$_toggleMixin_toggleShow() {
this.isShowing = !this.isShowing;
}
}
}
export { toggleMixin }
// example.vue
<template>
<div>
<h3 @click="$_toggleMixin_toggleShow">
<span v-if="isShowing">Click Me Again</span>
<span v-else>Click Me Please</span>
</h3>
</div>
</template>
<script>
import { toggleMixin } from "toggleMixin";
export default {
mixins: [toggleMixin] // 引入 toggleMixin 对象,data 和 methods 都会合并到当前组件中
};
</script>
规则1 - 业务逻辑复用代码放在 components/mixins 目录下
components
|-- mixins
|---- {name}Mixin.js
规则2 - Mixin 文件以及 Mixin 对象以 Mixin 后缀结尾
规则3 - 一个 Mixin 对象一个独立的文件
规则4 - Mixin 对象中的方法始终使用 $_ 前缀,并附带 Mixin 对象名以回避和其它作者的冲突
参加《编码规范》
进阶阅读 - 如果 mixin 对象与组件合并冲突怎么办?
如果选项的值是函数,则混合为一个数组;如果选项的值是对象,则混合为一个新对象,两个对象键名冲突时,取组件对象的键值对。
case1
选项的值是函数
示例
// mixin
const hi = {
mounted() {
console.log('hi from mixin!')
}
}
//vue instance or component
new Vue({
mixins: [hi],
mounted() {
console.log('hi from Vue instance!')
}
});
// hi from mixin!
// hi from Vue instance!
说明
mounted 钩子函数同名,混合后在 Vue 组件中的结果是一个数组,拥有两个 mounted 钩子函数,并且优先执行 mixin 中的钩子函数。
执行结果是先执行 mixin 中的 mounted 函数,然后执行 vue 组件中的 mounted 函数。
所以最终日志打印结果是:
hi from mixin!
hi from Vue instance!
case2
选项的值是对象
示例
//mixin
const hi = {
methods: {
sayHi: function() {
console.log('hi from mixin!')
}
},
mounted() {
this.sayHi()
}
}
//vue instance or component
new Vue({
mixins: [hi],
methods: {
sayHi: function() {
console.log('hi from Vue instance!')
}
},
mounted() {
this.sayHi()
}
})
// hi from Vue instance!
// hi from Vue instance!
说明
methods 是一个对象,混合后在 Vue 组件中的结果是一个新对象,其中 mixin 中的 sayHi 函数会被 Vue 组件中的同名函数重写。
执行结果是先执行 mixin 中的 mounted 函数,并调用 Vue 实例中的 sayHi 函数;然后执行 Vue 实例中的 mounted 函数并调用 Vue 实例中的 sayHi函数。
所以最终日志打印结果是:
hi from Vue instance!
hi from Vue instance!