手写实现vuex

这篇文章主要是说明如何手动实现vuex中的核心功能: state, mutations, actions

先看一下vuex的基本使用例子

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

let store = new Vuex.Store({
  // 全局状态
  state: {
    count: 0
  },
  // getters属性
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  },
  // 同步更新state状态
  mutations: {
    add(state) {
      state.count ++ ;
    }
  },
  // 异步更新state状态
  actions: {
    add(context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000)
    }
  }
})

export default store;


// main.js
import Vue from 'vue'
import store from './store'

new Vue({
  router,
  store, // 通过Vue构造函数将store挂载到Vue实例对象上
  render: h => h(App),
}).$mount('#app')
<!-- Home.vue -->
<div>
  <h2>使用store</h2>
  <p @click="$store.commit('add')">count: {{$store.state.count}}</p>
  <p @click="$store.dispatch('add')">async count: {{$store.state.count}}</p>
  <p>double count: {{$store.getters.doubleCount}}</p>

</div>

实现过程

1. 创建一个插件:声明Vuex类,并挂载$store

// myvuex.js
// 创建一个全局变量,存储Vue构造函数引用,避免使用import方式导入Vue
let Vue;

// 我们看到在store/index中,是通过new Vuex.Store({...})来生成store实例的,所以要创建一个Store类
class Store {
  // options是用来接收实例化传进来的state, getters, mutations, actions等
  constructor(options) {
  }
}

function install(_Vue) {
  Vue = _Vue;

  Vue.mixin({
    beforeCreate() {
      // 在根实例上找到store,并将其挂载到Vue原型上的$store,便于从this.$store获取对象
      if(this.$options.store) {
        Vue.prototype.$store = this.$options.store
      }
    }
  })
}

// Vuex
export default {
  Store,
  install
}
// 将导入的vuex文件改成自己实现的myvuex.js

// store/index.js

// import Vuex from 'vuex'
import Vuex from './myVuex/myvuex'

2. 创建响应式的state

在Vue实现数据响应式,可以有2种方法:

  • 使用new Vue中的data属性
  • 使用Vue.util.defineReactive(obj, property, initData)方式
class Store {
  // options是用来接收实例化传进来的state, getters, mutations, actions等
  constructor(options) {
    // 响应化处理state
    // 第1种方式
    this.state = new Vue({
      data: options.state
    })

    // 第2种方式
    // Vue.util.defineReactive(this, 'state', options.state)
  }
}

这时候,可以在组件中通过this.$store.state获取到状态了

3. 实现commit和dispatch方法

  • 保存mutations和actions对象
  • 实现commit方法,将this.state对象传到mutations的方法参数
  • 实现dispatch方法,将this对象传到actions的方法参数中,方便调用store实例上的commit方法
  • 在构造函数中,将commit和dispatch的this指向绑定指向store实例
class Store {

  constructor(options) {
    // 1. 保存mutations和actions
    this._mutations = options.mutations
    this._actions = options.actions

    // 4. 绑定函数的this指向
    this.commit = this.commit.bind(this)
    this.dispatch = this.dispatch.bind(this)


  }
  // 2. 实现commit方法:store.commit('add', 1)
  // type: mutation的类型,也就是mutations中的方法
  // payload: 载荷,也就是参数
  commit(type, payload) {
    const func = this._mutations[type]
    console.log('func:', func);
    if(func) {
      func(this.state, payload)
    }
  }

  // 3. 实现dispatch方法, store.dispatch('add', 2)
  dispatch(type, payload) {
    const asyncFunc = this._actions[type]
    console.log('asyncFunc:', asyncFunc);
    if(asyncFunc) {
      asyncFunc(this, payload)
      // 实际执行的是:
      // add(this) {
      //   setTimeout(() => {
      //     this.commit('add', 3)
      //   }, 1000)
      // }
      // 这里,this有可能会混乱,因为在异步操作时,setTimeout的this指向的是window,所以在异步回调里执行 this.commit会报错undefined
      // 所以要在构造函数中,将this.commit 和this.dispatch中this绑定到Store实例上
    }
  }
}

4. 实现单向数据流

我们知道用户是不能通过store.state方式修改状态的,只能通过mutation或actions来修改状态,所以我们要对this.state进行保护
所以不能直接对this.state进行响应式处理,而是另定义一个变量,然后对state属性使用存取器,get方法进行访问,set方法进行改变限制

class Store {
  constructor(options) {

    // this.state = new Vue({
    //   data: options.state
    // })

    // 我们不希望用户能通过store.state实例来访问或修改state属性,而是必须通过mutation或dispatch来修改
    this._vm = new Vue({
      data: {
        // 加两个$,Vue将不做代理,也就是用户不能通过this._vm['stateProperty']的方式访问到数据
        $$state: options.state
      }
    })
  }
  get state() {
    return this._vm._data.$$state
  }

  set state(v) {
    console.error("请不要直接使用this.$store.state方式直接修改数据!");
    // 使用 this.$store.state = {xxx} 时就会报错提示
  }
}

5. 实现getters

  • 定义一个computed对象
  • 遍历用户定义的getters对象,获取对应函数,并构造一个无参函数,赋予computed对象
  • 将computed对象挂载到Vue实例上
  • 为store实例上的getters定义只读属性,并将computed中的对象给赋予getters
class Store {
  constructor(options) {

    // 1. 保存用户定义的getters
    this._getters = options.getters

    // 实现getters计算属性
    // 2. 定义一个computed对象
    const computed = {}
    // 3. 定义getters对象
    this.getters = {}
    const store = this
    // 4. 遍历用户定义的getters
    Object.keys(this._getters).forEach(key => {
      // 5. 获取用户定义的getter
      const fn = store._getters[key]
      // 6. 转换成computed可以使用的无参形式
      computed[key] = function() {
        return fn(store.state)
      }
    })
    // 8. 为getters定义只读属性
    Object.defineProperty(store.getters, key, {
      get: () => store._vm[key]
    })

    // 我们不希望用户能通过store.state实例来访问或修改state属性,而是必须通过mutation或dispatch来修改
    this._vm = new Vue({
      data: {
        // 加两个$,Vue将不做代理,也就是用户不能通过this._vm['stateProperty']的方式访问到数据
        $$state: options.state
      },
      // 7. 将computed挂载到vue实例上,实现计算属性
      computed
    })
  }
}

完整代码

// myvuex.js
// 创建一个全局变量,存储Vue构造函数,避免使用import方式导入Vue
let Vue;

// 创建实例是new Vuex.Store({...}),所以要创建一个Store类
class Store {
  // options是用来接收实例化传进来的state, getters, mutations, actions等
  constructor(options) {

    // 保存mutations和actions
    this._mutations = options.mutations
    this._actions = options.actions
    this._getters = options.getters

    // 实现getters计算属性
    let 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)
      }
      // 为getters定义只读属性
      Object.defineProperty(store.getters, key, {
        get: () => store._vm[key]
      })
    })
    

    // 我们不希望用户能通过store.state实例来访问或修改state属性,而是必须通过mutation或dispatch来修改
    this._vm = new Vue({
      data: {
        // 加两个$,Vue将不做代理,也就是用户不能通过this._vm['stateProperty']的方式访问到数据
        $$state: options.state
      },
      computed
    })
  
    // 绑定函数的this指向
    this.commit = this.commit.bind(this)
    this.dispatch = this.dispatch.bind(this)
  }

  get state() {
    return this._vm._data.$$state
  }

  set state(v) {
    console.error("请不要直接使用this.$store.state方式直接修改数据!");
  }


  // 实现commit方法:store.commit('add', 1)
  // type: mutation的类型,也就是mutations中的方法
  // payload: 载荷,也就是参数
  commit(type, payload) {
    const func = this._mutations[type]
    console.log('func:', func);
    if(func) {
      func(this.state, payload)
    }
  }

  // 实现dispatch方法, store.dispatch('add', 2)
  dispatch(type, payload) {
    const asyncFunc = this._actions[type]
    console.log('asyncFunc:', asyncFunc);
    if(asyncFunc) {
      asyncFunc(this, payload)
      // 实际执行的是:
      // add(this) {
      //   setTimeout(() => {
      //     this.commit('add', 3)
      //   }, 1000)
      // }
      // 这里,this有可能会混乱,因为在异步操作时,setTimeout的this指向的是window,所以在异步回调里执行 this.commit会报错undefined
      // 所以要在构造函数中,将this.commit 和this.dispatch中this绑定到Store实例上
    }
  }
}

function install(_Vue) {
  Vue = _Vue;

  Vue.mixin({
    beforeCreate() {
      // 在根实例上找到store,并将其挂载到Vue原型上的$store,便于从this.$store获取对象
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store;
      }
    },
  });
}

// Vuex
export default {
  Store,
  install,
};
// store/index.js
import Vue from 'vue'
import Vuex from './myvuex'

Vue.use(Vuex);
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容

  • vuex官方文档 Vuex是什么? Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存...
    yutao618阅读 3,194评论 0 3
  • 为什么需要Vuex 通常 Vue 项目中的数据通信,我们通过以下三种方式就可以解决,但是随着项目多层嵌套的组件增加...
    尤小小阅读 1,079评论 1 5
  • ### store 1. Vue 组件中获得 Vuex 状态 ```js //方式一 全局引入单例类 // 创建一...
    芸豆_6a86阅读 730评论 0 3
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,934评论 0 7
  • 1. Vuex简介 Vuex是专门用来管理vue.js应用程序中状态的一个插件。他的作用是将应用中的所有状态都放在...
    黄黄黄大帅阅读 430评论 0 0