Mutation
- 触发mutations的第一种方式:
- this.$store.commit('add')
- commit 的作用,就是调用某个 mutations 函数。
//定义Mutations
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state){
state.count++
},
addN(state, step){
state.count += step
}
}
})
//触发mutations
methods: {
btnAdd(){
// 触发mutations的第一种方式,通过commit调用mutations中的add函数
this.$store.commit('add')
},
btnAddN(){
this.$store.commit('add', 3) //触发 mutations 时传递参数
}
}
2. 触发mutations的第二种方式:
//1.从vuex中按需导入 mapMutations 函数
import {mapMutations} from 'vuex'
//2.通过mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法。
methods: {
...mapMutations(['add', 'addN'])
}
Action
- 触发 actions 的第一种方式:
- this.$store.dispatch('addAsync')
- 触发 actions 异步任务时携带参数
//定义 Action
export default new Vuex.Store({
mutations: {
add(state){
state.count++
},
addN(state, step){
state.count += step
}
},
//在 actions 中不能直接修改 state 中的数据,
//还是要通过触发 mutations 的方式间接变更数据
actions: {
addAsync(context){
setTimeout(()=>{
context.commit('add')
}, 1000)
},
addNAsync(context, step){
setTimeout(()=>{
context.commit('addN', step)
}, 1000)
}
}
})
//触发 Action
methods: {
handle(){
this.$store.dispatch('addAsync') //触发 actions 的第一种方式
}
handle2(){
this.$store.dispatch('addNAsync', step)
}
}
- 触发 actions 的第二种方式:
<template>
//通过mapActions函数,将actions函数,映射为当前组件的methods方法,
//所以,subAsync就变成了methods中的函数,可以直接在template中使用。
<button @click="subAsync">-1 Async</button>
<button @click="subNAsync(5)">-N Async</button>
</template>
//1.从vuex中按需导入 mapActions 函数
import {mapActions} from 'vuex'
//2.通过mapActions函数,将需要的actions函数,映射为当前组件的methods方法。
methods: {
...mapActions(['subAsync', 'subNAsync'])
}
Getter
//定义 Getter
export default new Vuex.store({
state: {
count: 0
},
getters: {
showNum: state => {
return `当前最新数量是[${state.count}]`
}
}
})
//使用 getters 的第一种方式
this.$store.getters.showNum
//<h3>当前最新的count值:{{$store.state.count}}</h3>
<h3>{{$store.getters.showNum}}</h3>
//使用 getters 的第二种方式
import {mapGetters} from 'vuex'
methods: {
...mapGetters(['showNum'])
}
//<h3>当前最新的count值:{{count}}</h3>
<h3>{{showNum()}}</h3>