每一个 Vuex 应用的核心就是 store。store顾名思义就是存储仓库的 意思。
Vuex 的状态存储响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。
store中的getter state mutation action
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
可以通过 store.state 来获取状态,以及通过 store.commit 方法触发状态变更;
适合大型项目数据状态的监控**
1state
(单一状态树):每个一应用只能依赖一个,存储一些对象,数组等等。
在vue的组件中使用多个状态这样写代码有些沉郁
computed: {
count () {
return this.$store.state.count
}
}
我们可以借助mapState辅助我们生成计算属性。
import { mapState } from ‘vuex’
computed: {
count: state => state.count,
// 传字符串参数 ‘count’ 等同于 state => state.count
countAlias: ‘count’,
当要使用当前组件的locaCount
countPlusLocalState (state) {
return state.count + this.localCount
}
}
*2:getters
类似计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
Getter 也可以接受其他 getter 作为第二个参数:
getters: {
// …
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
3 mutation:
在vuex中改变状态唯一方法就是提交Mutation
Vuex 中的 mutation 非常类似于事件,每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
调用的时候不能直接调用¥.store.mutation.increment(),它像是注册事件,
store.commit(‘increment’)这样调用。
Payload:就是mutation的载荷,意味注册函数的第二个参数
mutations: {
increment (state, n) {
state.count += n
}
}
使用常量替代 Mutation 事件类型
const SOME_MUTATION = ‘SOME_MUTATION’
const store = new Vuex.Store({
state: { … },
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state) {
// mutate state
}
}
})
Action
mutation 中混合异步调用会导致你的程序很难调试。例如,当你调用了两个包含异步回调的 mutation 来改变状态,你怎么知道什么时候回调和哪个先回调呢?这就是为什么我们要区分这两个概念。在 Vuex 中,mutation 都是同步事务:
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit(‘increment’)
}
}
})
分发Action
store.dispatch(‘increment’)
还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit(‘increment’)
}, 1000)
}
}
Actions 支持同样的载荷方式和对象方式进行分发:// 以载荷形式分发
store.dispatch(‘incrementAsync’, {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: ‘incrementAsync’,
amount: 10
})]]
5:module其实只是解决了当state中很复杂臃肿的时候,module可以将store分割成模块,每个模块中拥有自己的state、mutation、action和getter。