混入
其实混入理解很简单,就是提取公用的部分,将这部分进行公用,这是一种很灵活的方式,来提供给 Vue 组件复用功能,一个混入对象能够包含任意组件选项。当组件使用混入对象时,全部混入对象的选项将被“混合”进入该组件自己的选项。vue
基础
接下来咱们来看一个很简单的例子,在 src/views/
新建 mixins.js
文件:web
// 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>
查看页面效果以下:微信
选项合并
当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。app
好比,数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先。编辑器
咱们仍是在 mixins.js
定义一个跟 TemplsteM.vue
里面相同的 firstName
属性:ide
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>
查看效果以下:flex
同名钩子函数将合并为一个数组,所以都将被调用。另外,混入对象的钩子将在组件自身钩子「以前」调用。
this
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
设置为 你好!
最后。让咱们尝试将策略更改成始终从子实例返回值:
本文分享自微信公众号 - 人生代码(lijinwen1996329ken)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。