1、vuex 直接修改state、commit 和dispatch 修改state 的用法及区别
1)可以直接使用 this.$store.state.变量 = xxx;
2)通过commit修改state
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
name:''
},
mutations: {
SET_NAME(state, name) {
state.name = name;
}
}
使用:commit提交触发mutations里方法
this.$store.commit("SET_NAME", 'xlt');
3)通过dispatch修改state
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
name:''
},
mutations: {
SET_NAME(state, name) {
state.name = name;
}
},
actions: {
set_name({
commit }, name) {
commit('SET_NAME', name)
}
}
使用:dispatch提交触发actions里方法
this.$store.dispatch("set_name", 'xlt');
2、区别:
1)commit方式是同步操作,dispatch方式是异步操作
3、总结:
1)都可以修改state里的变量,并且是响应式的(能触发视图更新)