Vuex 状态管理

2021-03-18  本文已影响0人  lowpoint

状态管理

组件间通信方式

ref两个作用

Vuex

使用场景

vuex严格模式
直接修改state的值会抛出错误
在开发环境中开启,在生产环境关闭严格模式(严格模式会深度检查状态树,检查状态改变,影响性能)

new Vuex.Store({
  strict:process.env.NODE_ENV !== 'production'
})

Vuex 插件

import Vue from 'vue'
import Vuex from 'vuex'

const myPlugin = store => {
 // store初始化后调用
  store.subscribe((mutation, state) => {
   //订阅 每次 mutation 之后调用 
   //mutation格式为{ type, payload } 可以通过type区分模块
  })
}


export default new Vuex.Store({
  plugins: [myPlugin] //注册插件
})

模拟一个Vuex

myVuex.js

let _Vue = null

class Store {
  constructor(options) {
    const {
      state = {},
      getters = {},
      mutations = {},
      actions = {}
    } = options

    this.state = _Vue.observable(state) //响应式处理
    this.getters = Object.create(null)
    Object.keys(getters).forEach(key => {
      Object.defineProperty(this.getters, key, {
        get: () => getters[key](state)
      })
    })

    this._mutations = mutations
    this._actions = actions
  }

  commit(type, payload) {
    this._mutations[type](this.state, payload)
  }

  dispatch(type, payload) {
    this._actions[type](this, payload)
  }

}

function install(Vue) {
  _vue = Vue
  _Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        _Vue.prototype.$store = this.$options.store
      }
    }
  })

}
export default {
  Store,
  install
}
上一篇下一篇

猜你喜欢

热点阅读