vuex状态管理器的好处:
1.数据公共存储
2.当数据变化通知页面更新
代码实现:
// 自己实现vuex
let Vue
class Store{
constructor(options) {
this.vm = new Vue({
data: {
state: options.state
}
})
// for getters
let getters = options.getters || {} // 拿到配置项中的getters,如果没有就写一个空对象
this.getters = {} // 定义一个getters
// 把getters中属性定义到this.getters
Object.keys(getters).forEach(getterName => {
Object.defineProperty(this.getters,getterName,{
get: () => {
return getters[getterName](this.state)
}
})
})
// for mutations
let mutations = options.mutations || {}
this.mutations = {}
Object.keys(mutations).forEach(mutationName => {
this.mutations[mutationName] = payload => {
mutations[mutationName](this.state,payload)
}
})
// for actions
let actions = options.actions || {}
this.actions = {}
Object.keys(actions).forEach(actionName => {
this.actions[actionName] = payload => {
actions[actionName](this,payload)
}
})
}
dispatch(type,payload) {
this.actions[type](payload)
}
commit = (type,payload) => {
this.mutations[type](payload)
}
get state() {
return this.vm.state
}
}
// 安装插件
// 目的: 让每一个组件都有$store
const install = (_Vue) => {
Vue = _Vue
// 给每一个组件都注册一个beforeCreate
Vue.mixin({
beforeCreate() {
// console.log(this.$options.name)
if(this.$options && this.$options.store) {
// 根
this.$store = this.$options.store
}else {
// 子
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default{
install,Store
}
// Object.defineProperty(obj,prop,descriptor)
// 参数:
// obj: 要在其上定义属性的对象
// prop: 要定义或修改的属性的名称
// decriptor:
// 将被定义或修改的属性描述符
// value: 属性值
// 参考连接
// https://wenku.baidu.com/view/8b23d95701768e9951e79b89680203d8ce2f6a03.html?fr=income1-wk_app_search_ctr-search