最近在做項(xiàng)目的時(shí)候家坎,研究了mixins嘱能,此功能有妙處。用的時(shí)候有這樣一個(gè)場景虱疏,頁面的風(fēng)格不同惹骂,但是執(zhí)行的方法,和需要的數(shù)據(jù)非常的相似做瞪。我們是否要寫兩種組件呢对粪?還是保留一個(gè)并且然后另個(gè)一并兼容另一個(gè)呢?
不管以上那種方式都不是很合理装蓬,因?yàn)榻M件寫成2個(gè)著拭,不僅麻煩而且維護(hù)麻煩;第二種雖然做了兼容但是頁面邏輯造成混亂牍帚,必然不清晰儡遮;有沒有好的方法,有那就是用vue的混合插件
mixins
暗赶”杀遥混合在Vue是為了提出相似的數(shù)據(jù)和功能,使代碼易懂忆首,簡單爱榔、清晰。
1.場景
假設(shè)我們有幾個(gè)不同的組件糙及,它們的工作是切換狀態(tài)布爾详幽、模態(tài)和工具提示。這些提示和情態(tài)動詞不有很多共同點(diǎn)浸锨,除了功能:他們看起來不一樣唇聘,他們不習(xí)慣相同,但邏輯是相同的柱搜。
//彈框
const Modal = {
template: '#modal',
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
},
components: {
appChild: Child
}
}
//提示框
const Tooltip = {
template: '#tooltip',
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
},
components: {
appChild: Child
}
}
上面是一個(gè)彈框和提示框迟郎,如果考慮做2個(gè)組件,或者一個(gè)兼容另一個(gè)都不是合理方式聪蘸。請看一下代碼
const toggle = {
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
}
}
const Modal = {
template: '#modal',
mixins: [toggle],
components: {
appChild: Child
}
};
const Tooltip = {
template: '#tooltip',
mixins: [toggle],
components: {
appChild: Child
}
};
用mixins引入toggle功能相似的js文件宪肖,進(jìn)行混合使用
2.可以合并生命周期
//mixin
const hi = {
mounted() {
console.log('this mixin!')
}
}
//vue組件
new Vue({
el: '#app',
mixins: [hi],
mounted() {
console.log('this Vue instance!')
}
});
//Output in console
> this mixin!
> this Vue instance!
先輸出的是mixins
的數(shù)據(jù)
3、可以全局混合(類似已filter)
Vue.mixin({
mounted() {
console.log('hello from mixin!')
},
method:{
test:function(){
}
}
})
new Vue({
el: '#app',
mounted() {
console.log('this Vue instance!')
}
})
會在每一個(gè)組件中答應(yīng)周期中的log健爬,同時(shí)里面的方法控乾,類似于vue的prototype添加實(shí)例方法一樣。
var install = function (Vue, options) {
// 1. 添加全局方法或?qū)傩? Vue.myGlobalMethod = function () {
// 邏輯...
}
// 2. 添加全局資源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 邏輯...
}
...
})
// 3. 注入組件
Vue.mixin({
created: function () {
// 邏輯...
}
...
})
// 4. 添加實(shí)例方法
Vue.prototype.$myMethod = function (options) {
// 邏輯...
}
}
有興趣的可以試試,若想了解更多請關(guān)注github賬號holidaying