其实混入理解很简单,就是提取公用的部分,将这部分进行公用,这是一种很灵活的方式,来提供给 Vue 组件复用功能,一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
接下来我们来看一个很简单的例子,在 src/views/
新建 mixins.js
文件:
// define a mixin object
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('hello from mixin!')
}
}
}
然后我们在 TemplateM.vue
使用 mixins
来混入 myMixins
:
<template>
<div class="template-m-wrap">
<input ref="input" />
</div>
</template>
<script>
import myMixins from './mixins'
export default {
name: "TemplateM",
mixins: [myMixins],
components: {
TestCom,
},
provide() {
return { parent: this };
},
data() {
return {
firstName: "dsdsdd",
lastName: "Ken",
};
},
methods: {
focusInput() {
this.$refs.input.focus()
}
},
mounted() {
this.focusInput()
}
};
</script>
查看页面效果如下:
当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。
比如,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先。
我们还是在 mixins.js
定义一个跟 TemplsteM.vue
里面相同的 firstName
属性:
const myMixin = {
data() {
return {
firstName: 'hello',
foo: 'abc'
}
}
}
export default myMixin
同样在 TemplateM.vue
使用混入:
<template>
<div class="template-m-wrap">
<input ref="input" />
</div>
</template>
<script>
import myMixins from './mixins'
export default {
name: "TemplateM",
mixins: [myMixins],
provide() {
return { parent: this };
},
data() {
return {
firstName: "dsdsdd",
lastName: "Ken",
};
},
methods: {
focusInput() {
this.$refs.input.focus()
}
},
mounted() {
this.focusInput()
}
};
</script>
查看效果如下:
同名钩子函数将合并为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子「之前」调用。
const myMixin = {
created() {
console.log('mixin hook called')
}
}
export default myMixin
查看效果如下:
由此我们可以得出结论:先执行混入对象的钩子,再调用组件钩子。
值为对象的选项,例如 methods
、components
和 directives
,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
const myMixin = {
methods: {
foo() {
console.log('foo')
},
focusInput() {
console.log('from mixin')
}
}
}
export default myMixin
查看浏览效果如下:
你还可以使用全局混入的方式,在 src/main.js
:
import { createApp } from 'vue/dist/vue.esm-bundler.js'
import App from './App.vue'
import router from './router'
import store from './store'
let app = createApp(App)
app.use(store).use(router).mount('#app')
app.mixin({
created() {
console.log("全局混入")
}
})
查看效果如下:
混入也可以进行全局注册。使用时格外小心!一旦使用全局混入,它将影响「每一个」之后创建的组件 (例如,每个子组件)。
自定义选项将使用默认策略,即简单地覆盖已有值。如果想让自定义选项以自定义逻辑合并,可以向 app.config.optionMergeStrategies
添加一个函数:
import { createApp } from 'vue/dist/vue.esm-bundler.js'
import App from './App.vue'
import router from './router'
import store from './store'
let app = createApp(App)
app.use(store).use(router).mount('#app')
app.config.optionMergeStrategies.custom = (toVal, fromVal) => {
console.log(fromVal, toVal)
// => "goodbye!", undefined
return fromVal || toVal
}
app.mixin({
custom: 'goodbye!',
created() {
console.log(this.$options.custom) // => "hello!"
}
})
查看浏览效果:
如你所见,在控制台中,我们先从 mixin 打印 toVal
和 fromVal
,然后从 app
打印。如果存在,我们总是返回 fromVal
,这就是为什么 this.$options.custom
设置为 你好!
最后。让我们尝试将策略更改为始终从子实例返回值: