Vue中的store
1、介绍
每一个vuex的应用的核心就是store(仓库)。“store”基本上就是一个容器,它包含着应用中大部分的状态(state).Vuex和单纯的全局对象有以下两种不同:
-
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
-
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
-
2、核心介绍
-
State :
-
就是实际存储的变量
-
使用方法
-
state:{ num: 1, str: 'aaa', }
-
-
调用方法
-
store.state.num
-
this.$store.state.num
-
-
-
getters :
-
相当于set、get中的get,这个有两个可选的参数,state、getters,分别可以获取state的变量和其他的getters.
-
使用方法
-
getters:{ doneTodos(state, getters){ return getters.doneTodos.length } }
-
-
调用方法
-
store.getters.doneTodos
-
-
-
Mutation(commit):
-
相当于set、get中的set,这是在vuex中唯一需改state的方式,但是不支持异步的操作
-
使用方法
-
mutations:{ increment(state, params){ state.num = param } }
-
-
调用方法
-
store.commit('increment')
-
-
-
actions:
-
和mutations类似。不过actions支持异步操作,第一个参数默认是和store具有相同参数属性的对象,因此你可以调用
context.commit
提交一个 mutation,或者通过context.state
和context.getters
来获取 state 和 getters。 -
使用方法
-
actions:{ increment(context){ context.commit('increment') } }
-
-
分发action
-
store.dispatch('increment')
-
注:mutation必须同步执行,action就不受约束!我们可以在action内部执行异步操作
-
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
-
-
-
Module
-
当应用中所有的状态集中到一个比较大的对象中,当应用变得非常复杂时,store对象就有可能变的相当臃肿,为了解决这个问题,Vuex允许我们将store分割成模块(module).每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。
-
使用方法
-
const moduleA = { state: () => ({ ... }), mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: () => ({ ... }), mutations: { ... }, actions: { ... } } const store = createStore({ modules: { a: moduleA, b: moduleB } }) store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态
-
const moduleA = { state: () => ({ count: 0 }), mutations: { increment (state) { // 这里的 `state` 对象是模块的局部状态 state.count++ } }, getters: { doubleCount (state) { return state.count * 2 } } }
-
-
-