vuex

2018-11-08  本文已影响0人  恒星的背影

State

mapState 辅助函数:

import { mapState } from 'vuex'

computed: mapState({
  count(state, getters) {
    return getters['selectCount']
  }
})

Getter

类似于计算属性:

selectCount(state, getters) {
  return state.count + 1;
}

mapGetters 辅助函数:

mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

Mutation

mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

多个参数时必须使用对象的形式传入,因为 commit 不接受多个参数:

store.commit('increment', {
  amount: 10
})

为了 devtools 的调试,约定 mutation 必须是同步函数

Action

可以包含异步操作,约定通过提交 mutation 变更状态

actions: {
  increment (context) {
    context.commit('increment')
  }
}

context 与 store 具有相同的属性和方法
更方便的写法:

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

使用时可以传参:

store.dispatch('incrementAsync', {
  amount: 10
})

Module

可以把 store 分割成模块,每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

对于模块内部的 action,根节点状态则为 context.rootState:

actions: {
  increment ({ state, commit, rootState }) {

  }
}

对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

getters: {
  sumWithRootCount (state, getters, rootState) {
    return state.count + rootState.count
  }
}

可以通过添加 namespaced: true 的方式使其成为带命名空间的模块:

模块内的 state 已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
getters['account/isAdmin']
dispatch('account/login')
commit('account/login')

使用 namespaced 不会影响模块内部的代码
若需要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatch 或 commit 即可

dispatch('someAction')   // -> 'foo/someOtherAction'
dispatch('someAction', null, { root: true })   // -> 'someOtherAction'

项目结构

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

上一篇 下一篇

猜你喜欢

热点阅读