vuex的基本规则

Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:

应用层级的状态应该集中到单个 store 对象中。

提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。

异步逻辑都应该封装到 action 里面。

state [type: Object]

const store = new Vuex.Store({
    state: {
        count: 1
    }
    mutations: ...
})

modules

const moduleA = {
    state,
    mutations,
    actions, // 可无
    getters, // 可无
    modules  // 可无, 可嵌套
}

const moduleB = {
    state,
    mutations,
    actions,
    getters
    modules
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
store.state.a; // -> moduleA 的状态
store.state.a; // -> moduleB 的状态

getter

const store = new Vuex.Store({
    state: { ... },
    getter: {
        exampleGetter(state, getters) {
            return 
        }
    }
})

const module = {
    state: ...
    getter: {
        exampleGetter(state, getters, rootState)
    }
}

mutations [type: string]: Function

// like Reducer
const store = new Vuex.Store({
  ...
  mutations: {
    increment (state, playload) {
      // 变更状态
      state.count++
    }
  }
})

 

mutation 必须是同步函数

devtools 不知道什么时候回调函数实际上被调用 —— 实质上任何在回调函数中进行的的状态的改变都是不可追踪的

actions

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象?

支持异步:

  1. promise
  2. async / await
function (context) {}

context = { state, rootState, getters, commit, dispatch}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值