vuex直接修改state、commit和dispatch修改state的区别
1)可以直接使用 this.$store.state.变量 = xxx;
2)通过commit修改state
1 2 3 4 5 6 7 8 9 10 11 12 | import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { name: '' }, mutations: { //类似method SET_NAME(state, name) { state.name = name; } } |
使用:commit提交触发mutations里方法
1 | this .$store.commit( "SET_NAME" , 'xlt' ); |
3)通过dispatch修改state
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { name: '' }, mutations: { //类似method SET_NAME(state, name) { state.name = name; } }, actions: { //类似method set_name({ commit }, name) { commit( 'SET_NAME' , name) } } |
使用:dispatch提交触发actions里方法
1 | this .$store.dispatch( "set_name" , 'xlt' ); |
区别
- commit方式是同步操作
- dispatch方式是异步操作
总结
都可以修改state里的变量,并且是响应式的(能触发视图更新)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。