持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情
在上一篇我们用官网vuex实现一个简单功能,这里我们自己写一个vuex来替换官方的。
我们可以分析一下官方的vuex都使用了哪些方法,1 在main.js 用到了app.use(store) 用到了vue的use方法,写过插件的都知道,用到了use就说明,vuex返回的对象里肯定有install 2 我们还在vuex里解构出了createStore,说明还有createStore方法,3 在组件里还在vuex解构除了useStore方法,也要实现这个功能, 新建一个vuex文件夹
然后在main.js也改下vuex的引用
import store from './store'
介绍写法
import { reactive, inject } from 'vue'
首先新建一个 createStore
export function createStore(options) {
// 大家在初始化vuex都是需要有state mutations actions modules getters这5个属性(这里我们只实现3个基本的)
需要返回一个对象 这个对象要包括一个install 这个在上面说过
return new Store(options) //
}
// 这里我们要实现Store方法 (他是一个类)
function Store({ state, mutations, actions }) { // 解构出来
this.state = state;
this.mutations = mutations,
this.actions = actions
}
// 在Store原型上添加install方法 app.use要用到
Store.prototype.install = function() {
let that = this
// 需要新建一个对象
var store = {};
store.state = reactive(this.state)//store.state要求必须是响应式的对象 在vue3中就比较简单
// 直接结构出reactive 就可以转换为响应式数据了
// 开始添加commit事件
store.commit = function(mutationName,args) {
// 触发你之前初始化的函数
that.mutations[mutationName](args)
}
// actions 也是同理
// 这两个激活事件其实都是激活的你在store文件夹里初始化的方法
store.dispatch = function(type,args) {
that.actions[type]({ commit: this.commit, state: this.state },args)
}
// 我们利用vue3 信息传递 provide 注册一个属性来实现
app.provide('store',store)
}
// 还有一个方法我们需要在创建一个useStore方法 把store返回出去
export function useStore() {
// 因为我会先执行install方法 所有我们这里vue解构的inject也可以拿到provide注册属性
return inject('store')
}