手写vuex

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值