本文参考珠峰架构公开课之
vuex
实现原理
vuex
是基于vue
框架的状态管理。
如何在vue
项目中初始化vuex
?
-
通过
Vue.use(vuex)
注册。 -
通过实例化
vuex
里的Store
,并传入options
即可使用。import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {}
});
既然vuex
是通过vue.use
注册,并且通过vuex.Store
实例化来生成,那它的底层是包含一个Store
的实例,并且有个注册组件的install
方法。
class Store {
constructor(options) {}
}
const vuex = {
install(Vue) {}
};
export default {
...vuex,
Store,
};
状态保存在什么地方?
在vue
中是通过this.$store.state
访问。既然通过this
访问全局状态,分析可以有两种方式实现:
$store
是绑定在vue
的原型上,即通过Vue.prototype.$store
绑定。- 通过
Vue.mixin
给所有的组件的属性上绑定$store
。
实际上vuex
是通过Vue.mixin
来实现保存全局状态的。那为什么不能绑定在vue
的prototype
上呢?看下例:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
new Vue1({
store,
render: h => h(App)
}).$mount('#app')
new Vue2({
render: h => h(App)
}).$mount('#app2')
如果碰到一个项目中vue
被实例化了两次,这时候将$store
保存在vue.prototype
上的话,Vue1
和Vue2
会共享一个$store
,这样会造成状态冲突。实例化出来的vue
,他们的状态应该是隔离的。所以通过Vue.mixin
给当前vue
实例下所有的组件绑定$store
属性,实现代码如下:
const vuex_install = {
install(vue) {
vue.mixin({
beforeCreate() {
if (this.$options && this.$options.store) {
this.$store = this.$options.store;
} else {
this.$store = this.$parent && this.$parent.$store;
}
},
});
},
};
1. 为什么要放在beforeCreate
中注册?
个人理解是因为在beforeCreate
中注册$store
的话就可以在created
中使用$store
。
2. $store
是如何绑定到各个组件上的?
通过Vue.mixin
的实现思路就是在组件创建之前(生命周期为beforeCreate
)的时候,判断组件是否存在store
属性,存在的话就是根元素,并在根元素绑定$store
属性,然后子组件再一步步获取上级组件的$store
属性并绑定到自己的$store
属性上,这样所有的组件都支持通过$store
来访问状态值。
最后编辑于:2025-04-21 10:38:03
© 著作权归作者所有,转载或内容合作请联系作者

喜欢的朋友记得点赞、收藏、关注哦!!!