完整购物车demohttps://gitee.com/cloveryuan/cartdemo
![](https://img.haomeiwen.com/i7522654/04148349a752b6c0.png)
- 统一的导入modules
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
}, {})
- 缓存写入自己的plugins
Vuex的插件就是一个函数,这个函数接受一个store参数,这个参数可以订阅一个函数,让这个函数在所有的mutation结束之后执行。
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
- 手写简单版vuex
vuex由install,和Store组成
Store是一个包含{state,getters,mutations,actions,还有commit,dispatch方法}
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 }
网友评论