mutation
mutation用于变更store中的数据
1、只能通过mutation变更store数据,不可以直接操作store中的数据。
this.$store.state.count++
2、通过mutation这种方式,可以集中监控所有数据的变化
想要改变count的值,可以:
const store = new Vuex.store({
state: {
count: 0
},
mutations: {
add(state) {
state.count++
}
}
})
在组件中可以调用函数,进行使用
methods: {
handle() {
this.$store.commit('add')
}
}
如何在触发mutations时传递参数:
const store = new Vuex.store({
state: {
count: 0
},
mutations: {
addN(state, step) {
state.count += step
}
}
})
methods: {
handle() {
this.$store.commit('addN',3)
}
}
this.$store.commit()是出发mutations的一种方式,还有第二种方式:
1、从vuex中按需导入mapMuations 函数
import { 'mapMutations' } from 'vuex'
通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法
2、将指定的mapMutations函数,映射为当前组件的methods函数
methods: {
...mapMutations(['add','addN'])
handle() {
this.add() 直接调用映射过来的mutation函数
}
}
不要在mutations函数中,执行异步操作,
action
action用于处理异步任务
如果通过异步操作变更数据,必须通过action,而不能使用mutation,但是action中还是要通过触发mutation的方式间接变更数据。
const store = new Vuex.store({
state: {
count: 0
},
mutations: {
add(state) {
state.count ++
}
},
actions: {
addAsync(context) {
setTimeout(() => {
context.commit('add')
},1000)
}
}
})
组件中,触发action,第一种方式:
methods: {
handle () {
this.$store.dispatch('addAsync')
}
}
第二种:
1、从vuex中按需导入mapActions 函数
import { 'mapActions' } from 'vuex'
通过刚才导入的mapActions函数,将需要的actions函数,映射为当前组件的methods方法
2、将指定的mapActions函数,映射为当前组件的methods函数
methods: {
...mapActions(['addAsync'])
handle() {
this.addAsync() 直接调用映射过来的actions函数
}
}
如何触发actions异步任务是携带参数:
const store = new Vuex.store({
state: {
count: 0
},
mutations: {
addN(state, step) {
state.count += step
}
},
actions: {
addAsync(context,step) {
setTimeout(() => {
context.commit('addN',step)
},1000)
}
}
})
触发action
methods: {
handle () {
this.$store.dispatch('addAsync', 5)
}
}
getter
getter用于对store中的数据进行加工处理形成新的数据。getter不会改变state中的数据,只是加工包装
1、getter可以对store中已有的数据加工处理之后形成新的数据,类似vue的计算属性。
2、store中数据发生变化,getter的数据也会跟着变化。
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
showNum(state): {
return '当前最新的数据是'+ state.count
}
}
})
使用getters的第一种方式:
this.$store.getters.showNum
第二种方式:
import { mapGetters } from 'vuex'
computed: {
...mapGetters({'showNum'})
}