vuex我也能手写了!

前言

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

正文

实现vuex

vuex的基本用法如下:

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

步骤一

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

js 复制代码
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关键字去声明一个函数,直接解决问题!

js 复制代码
get state() { 
    return this._state.data
}

步骤三

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

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

步骤四

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

js 复制代码
function useStore() {
  return inject('_store_')
}

步骤五

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

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

结

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

js 复制代码
//手动实现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
}
相关推荐
usdoc文档预览4 小时前
USDOC系列之PPT文件在线编辑-VUE前端实现在线浏览器在线编辑PPT文档
前端·vue.js·编辑器·office365·ppt在线编辑·office文件在线编辑·文件在线编辑
Java小卷4 小时前
面向 schema 编程,轻松搞定 Element 虚拟化表格复杂应用场景
vue.js·低代码·element
仨孩子的爹5 小时前
Lodop、hiprint 与 vue-print-designer:打印控件选型对比
vue.js
ruanno_top8 小时前
四个 canvas 组件,在 2 倍屏上一直是糊的
vue.js
ruanno_top9 小时前
一个脏数据能让整条折线消失:图表组件的四种数据契约
vue.js
FlyWIHTSKY1 天前
vue2和vue3有什么区别,用法上有哪些区别
前端·javascript·vue.js
ruanno_top1 天前
能点,但 Tab 不到:两个组件把「可操作」做了一半
vue.js
爱吃烧烤的技术渣1 天前
别再手写 CRUD 了:我把 Element Plus 的工作量压缩成一份列 schema
前端·vue.js
徐小夕1 天前
万字长文!DeepSeek Super-agent × 企业知识库架构深度拆解与落地实践
前端·vue.js·github
ruanno_top2 天前
倒计时该用 deadline 还是每秒减一?我把两种写法都跑了一遍
vue.js