详解如何实现一个简单的 vuex

2020-06-16 06:08:56易采站长站整理

methods: {
handleClick () {
this.$store.state.count += 1
}
}
}

// 子组件 b
const childB = {
template: '<div>count: {{ count }}</div>',
computed: {
count () {
return this.$store.state.count
}
}
}

new Vue({
el: '#app',
components: {
'child-a': childA,
'child-b': childB
},
store: store
})

看到代码里还有一个 Store 待实现。所需要的参数,因为这里懒得用 Vue.use() ,所以直接将 Vue 作为参数传入以供使用,然后第二个参数跟我们使用 vuex 传入的参数一致。

Store 的实现

接下来就是 Store 的实现,两步实现:

创建一个 bus 实例;
让子组件都能访问到 this.$store。

第 1 步骤上面已经有了,第 2 步骤主要用到了 Vue.mixin 来全局混入,但仅仅只是找到有 store 的根实例并赋值 Vue 原型上的 store,也能够让根实例 app 不用专门写 mixins 混入。


class Store {
constructor (Vue, options) {
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
}
}
})
}
}

实现的 Store 就是一个简单的 “vuex”,它拥有了 vuex 的 state,足够让非父子组件之间进行简单通信。

在 Store 的构造函数里创建一个 bus 实例,并将其注入 Vue 的原型,实现了组件都能访问到 this.$store 即 bus 实例。 this.$store 就是一个 Vue 实例,所以访问了 this.$store.state.count 实际上就是访问到了 data,从而实现了非父子组件之间的响应同步。全部源码参考这里 。