这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战
导读
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
这次手写一个简版的vuex ,我们通过其基本的用法,来慢慢展开源代码的书写。让我们对Vuex有个更深刻的认识吧!在项目中能够更自如的运用vuex的特性把。
vuex的使用步骤
1. 安装插件
Vue.use(Vuex)在vue项目里安装插件
在这里呢,导出的Vuex需要实现一个install方法
// 插件需要实现的install方法
function install(_Vue) {
// 传入_Vue 保存下来
Vue = _Vue;
Vue.mixin({
beforeCreate() {
// 在跟组件创建的之前 挂载一下$store供全局使用
if (this.$options.store) {
Vue.prototype.$store = this.$options.store;
}
},
});
}
// 因为new Vuex.Store() 所以将Store 作为默认对象的一个属性和install 一起到处
export default { Store, install };
2. 然后实例化Store
store = new Vuex.Store(store)
3. 实例化完成后传入store到Vue里
4. 实现commit , dispatch
new Vue({store})
class Store {
constructor(options) {
// 选项做保存
this.$options = options;
this._mutations = this.$options.mutations;
this._actions = this.$options.actions;
this._getters = this.$options.getters;
const computed = {};
this.getters = {};
const store = this;
Object.keys(this._getters).forEach((key) => {
// 获取用户定义的getter
const fn = store._getters[key];
// 转换computed可以使用无参数形式
computed[key] = function () {
return fn(store.state);
};
// 为getter定义只读属性
Object.defineProperty(store.getters, key, {
get: () => store.vm[key],
});
});
// state对象是响应式的 需要触发页面渲染
// new Vue() 或者 Vue.util.defineReactive()都可以创建响应式对象
this.vm = new Vue({
data: {
$$state: this.$options.state,
},
computed
});
// 注意: dispatch是异步的需要强绑定当前this指向
this.commit = this.commit.bind(this);
this.dispatch = this.dispatch.bind(this);
}
get state() {
// 避免用户直接修改state 只能获取
return this.vm._data.$$state;
}
commit(type, payload) {
// 从mutations里获取action
if (!this._mutations[type]) {
console.error("");
return;
}
this._mutations[type](this.state, payload);
}
dispatch(type, payload) {
// 从action取出type
if (!this._actions[type]) {
console.error("");
return;
}
this._actions[type](this, payload);
}
}
结束语
简写版Vuex 到这里就结束了,实现了commit, dispatch, getters的功能,大家如果有什么疑问可以在文章下方留言哦。
如果您喜欢我的文章,可以[关注⭐]+[点赞👍]+[评论📃],您的三连是我前进的动力,期待与您共同成长~