【Vuex】dispatch和commit来调用mutations的区别
Action
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
dispatch 推送一个action
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
commit 推送一个mutation
main.js中
import Vuex from 'vuex' Vue.use(vuex); const store = new Vuex.store({ state: { nickName: "", cartCount: 0 }, mutations: { updateUserInfo(state,nickName) { state.nickName = nickName; }, updateCartCount(state,cartCount) { state.cartCount += cartCount; } }, actions: { updateUserInfo(context) { context.commit("updateUserInfo"); }, updateCartCount(context) { context.commit("updateCartCount"); } } }) new Vue({ el: "#app", store, router, template: '<App/>', components: {App} })
组件中:
methods: { increment(){ this.$store.dispatch("updateUserInfo", 'nick'); //this.$store.commit("increment", 'nick'); }, decrement() { this.$store.dispatch("updateCartCount", 1); // this.$store.commit("decrement", 1); } }
mutations: { updateUserInfo(state, payload) { state.userId = payload.userId; state.avatar = payload.avatar; }, updateEnergy(state, payload) { state.energy = payload; } }, actions: { async pageBeforeRender({ dispatch }) { // 当页面渲染前,会调用该接口查询数据 return await dispatch('requestUserInfo'); }, async requestUserInfo({ commit }) { try { const payload = await ap.getUserInfo(); commit('updateUserInfo', payload); } catch (ex) { ap.showToast({ content: '请求失败', type: 'fail' }); } }
区别:
dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('mutations方法名',值)
commit:同步操作,写法:this.$store.commit('mutations方法名',值)
相关推荐
CSCCockroach 2020-09-15
lbPro0 2020-07-05
MrSunOcean 2020-06-21
lylwanan 2020-06-14
Callmesmallpure 2020-05-31
ShaLiWa 2020-05-25
墨龙吟 2020-04-24
MrSunOcean 2020-04-24
H女王范儿 2020-04-22
lbPro0 2020-04-16
ShaLiWa 2020-02-29
ShaLiWa 2020-01-17
MrSunOcean 2020-01-03
lbPro0 2020-01-01
H女王范儿 2019-12-29