likes
comments
collection
share

vuex我也能手写了!

作者站长头像
站长
· 阅读数 33

前言

vuex给组件通信带来了极大便利,想想我们是不是也能打造一个简易版的vuex呢?

正文

实现vuex

vuex的基本用法如下:

  1. 首先引入createStore,调用createStore(传入一个对象作为参数)并将结果store这个实例对象抛出,在main.js中引入store后将它use掉。
  2. 访问仓库数据只需引入useStore调用它后就能访问了。
  3. 触发mutations中的方法需使用commit('方法名' , 参数)来触发

步骤一

我们根据它的基本用法,我们使用先搭建一个基本框架

class Store {
    constructor(options) {
        this.$options = options  //一个对象
        this._state = reactive({  //响应式数据源
          data: options.state()
        })
        this._mutations = options.mutations
    }

function createStore(options) {
  return new Store(options)
}

export {
  createStore
}

步骤二

我们访问仓库数据源会直接store.state,但是这里访问则是store._state.data,那么可以使用get关键字去声明一个函数,直接解决问题!

get state() { 
    return this._state.data
}

步骤三

因为 Vuex 插件需要被 use() 才能被使用,所以必须要有个 install 方法,其中接收的参数app就是Vue,我们利用 Vue 的provide方法将其提供出去

 install(app) {   //将store挂载到全局   app就是vue
    app.provide('_store_', this)
 }

步骤四

为了能获取到仓库数据,我们需要打造一个useStore方法并抛出,也就是说把这个仓库的实例对象注入到组件中。(const store = useStore() 相当于 inject('store'))

function useStore() {
  return inject('_store_')
}

步骤五

我们要访问仓库中mutations的方法得使用store.commit()进行触发,它接收一个函数名,其它为剩余的参数

 commit(method, ...args) {  //触发mutations中的方法
    const fn = this._mutations[method]  //获取mutations中的方法
    fn && fn(this.state, ...args)  //如存在则调用mutation中的方法,这个方法接收state和剩余参数
 }

这里只打造了可以访问数据源和触发mutation中方法的简易版vuex,其它模块的实现也不会太难,最后附上整份代码:

//手动实现vuex
import { reactive, inject } from 'vue'
class Store {
   constructor(options) {
        this.$options = options  //一个对象
        this._state = reactive({  //响应式数据源
          data: options.state()
        })
        this._mutations = options.mutations
   }

  get state() {
    return this._state.data
  }

  commit(method, ...args) {  //触发mutations中的方法
    const fn = this._mutations[method]  //获取mutations中的方法
    fn && fn(this.state, ...args)  //如存在则调用这个方法
  }

  install(app) {   //将store挂载到全局   app就是vue
    app.provide('_store_', this)
  }

}

function createStore(options) {
  return new Store(options)
}

function useStore() {
  return inject('_store_')
}

export {
  createStore,
  useStore
}
转载自:https://juejin.cn/post/7265999062242918460
评论
请登录