核心:store(仓库)
状态存储是响应式的
改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。
使用
安装vuex创建store,在main.js引入import store from './store'
Store
创建store
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state:{
count:1,
},
mutations:{
increment(state){state.count++;},
reduce(state){state.count--;}
},
})
export default store;
通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更。
//由于 store 中的状态是响应式的,在组件中调用 store 中的状态简单到仅需要在计算属性中返回即可。触发变化也仅仅是在组件的 methods 中提交 mutation。
computed:{
count(){return this.$store.state.count}
},
methods:{
changeBtn(){this.$store.commit('increment')},
reduce(){this.$store.commit('reduce')}
}
mapState
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。使用 **mapState** 辅助函数帮助我们生成计算属性
// 使用 mapState 辅助函数帮助我们生成计算属性
import {mapState} from 'vuex';
//修改 使用辅助函数
computed:mapState({
count:state => state.count
}),
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
对象展开运算符
mapState返回一个对象,如何将它与局部计算属性混合使用?
使用工具函数将多个对象合并为一个
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
getter
从 store 中的 state 中派生出一些状态,像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
egOne:
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
//Getter 接受 state 作为其第一个参数:
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
//Getter 也可以接受其他 getter 作为第二个参数:
doneTodosCount:(state,getters) => {
return getters.doneTodos.length
}
//通过store.getters访问
console.log(this.$store.getters.doneToDos)
mapGetters
将 store 中的 getter 映射到局部计算属性:
//store下index.js
state:{
...
name:'oldName',
},
mutations:{
updateName(state){
state.name = 'newName'
}
}
/*现在假设逻辑有变,我们最终期望得到的数据(computed中的getName),是基于 this.$store.state.name 上经过复杂计算得来的,刚好这个getName要在好多个地方使用,那么我们就得复制好几份。*/
vuex 给我们提供了 getter来解决这个问题,可以认为是 store 的计算属性,请看代码:
getters:{
...
getReverseName:state => {
return state.name.split('').reverse().join('')
}
}
//使用
computed:{
//相当于替换了
...mapGetters(['getName'])
/*getName(){
// return this.$store.state.name
return this.$store.getters.getReverseName
}*/
}
getter总结:getters主要是用来过滤和重组,这些事件最好也是能在计算属性中完成,用于监听事件变化的。
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
载荷
你可以向 store.commit 传入额外的参数,即 mutation 的 载荷
// ...
mutations: {
increment (state, n) {
state.count += n
}
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', 10)
//大多数情况下,载荷应该是一个对象
store.commit('increment', {amount: 10})
Mutation 必须是同步函数
在组件中提交 Mutation
this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。
Action
Action 类似于 mutation,不同在于:
-
Action 提交的是 mutation,而不是直接变更状态。
-
Action 可以包含任意异步操作。
actions:{ increment(content){ content.commit('increment') } }
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
分发 Action
通过 store.dispatch 方法触发:
store.dispatch('increment')
action不受同步执行限制,内部执行一部操作
购物车示例,涉及到调用异步 API 和分发多重 mutation:
actions: {
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit(types.CHECKOUT_REQUEST)
// 购物 API 接受一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失败操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
Module
将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态