前端小白成长--vuex

2020-08-14  本文已影响0人  Clover园

完整购物车demohttps://gitee.com/cloveryuan/cartdemo

image.png
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')// $1是正则里的捕获,就是前面()里的东西
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})
const myPlugin = store => {
  // 当store初始化后调用
  store.subscribe((mutation, state) => {
    // 每次mutation之后调用
    // mutation的格式为{ type, payload }
  })
}

eg:购物车的car模块

// 自定义插件carPlugin,只有car模块里面调用motution,就保存购物车最新详情
const carPlugin = store => {
  store.subscribe((mutation, state) => {
    if (mutation.type.startsWith('cart/')) {
      window.localStorage.setItem('car-products', JSON.stringify(state.cart.cartProducts))
    }
  })
}

const store = new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  modules,
  plugins: [carPlugin]
})
export default store
let _Vue = null // 存放vue构造函数
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({ // 只有实例中$options才有store,组件$options中没有,只需要实例化的时候调用install就好了
    beforeCreate () {
      if (this.$options.store) {
        _Vue.prototype.$store = this.$options.store // 实例上的store注入原型上去,这样可以直接this.$store获取到store
      }
    }
  })
}
export default { install, Store }

上一篇 下一篇

猜你喜欢

热点阅读