vuex 的 dispatch 和 commit 的区别 vue
import Vuex from 'vuex'Vue.use(vuex);const store = new Vuex.store({ state: { nickName: "", cartCount: 0 }, mutations: { updateUserInfo(state,nickName) { state.nickName = n
·
mian.js中:这样写 下面引入一下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);
}
}
区别:
dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('mutations方法名',值)
commit:同步操作,写法:this.$store.commit('mutations方法名',值)
更多推荐
已为社区贡献3条内容
所有评论(0)