隨著前端業(yè)務日益復雜,組件數(shù)量不斷增加,組件之間的通信變得越來復雜,兄弟組件之間跨級傳參,狀態(tài)修改得追蹤,都是一個難題 VUEX解決了這個問題,然后如何實現(xiàn)一個簡單得vuex呢,state是如何在不同組件之間被watch得,值得去研究。
vue mixin 了解一下
混入 (mixins) 是一種分發(fā) Vue 組件中可復用功能的非常靈活的方式。
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
輸出:// => "hello!"
全局混入: 在new vue對象時,會自動執(zhí)行created這個方法,如果new vue里面還有create 就會先執(zhí)行mixin,再執(zhí)行實例里面的create.
// 子組件 a
const childA = {
data: function(){
return {a:1}
},
created: function(){
console.log('childA',this);
},
template: '<button @click="handleClick">click me</button>',
methods: {
handleClick () {
console.log(this)
this.$store.state.count += 1
}
}
};
// 子組件 b
const childB = {
data: function(){
return {b:2}
},
created: function(){
console.log('childB',this);
},
template: '<div>count: {{ count }}</div>',
computed: {
count () {
return this.$store.state.count
}
}
};
class Store {
constructor (Vue, options) {
console.log('new Vue');
var bus = new Vue({
data: {
state: options.state
}
});
this.install(Vue, bus)
}
install (Vue, bus) {
Vue.mixin({
beforeCreate () {
if (this.$options.store) {
Vue.prototype.$store = bus
}
}
})
}
};
const store = new Store(Vue, {
state: {
count: 0
}
})
new Vue({
el: '#app',
data: function(){
return {c:1}
},
created: function(){
console.log('vue',this);
},
components: {
'child-a': childA,
'child-b': childB
},
store: store
});
代碼解析:
- 初始化VUE的時候執(zhí)行created的方法,Vue.prototype.$store = bus,相當于在原型鏈上添加一個共享對象。
- Vue 和 VueComponent 的原型鏈上指向同一個store,這樣不同組件之間就能共享一個state。
- $strore 指向的還是一個vue對象,保證修改可以被監(jiān)聽到。
著作權聲明
原文地址: 覃國雷的博客