混入
其實混入理解很簡單,就是提取公用的部分,將這部分進行公用,這是一種很靈活的方式,來提供給 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源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。