vuex直接修改state、commit和dispatch修改state的用法及区别说明

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: {//类似method
    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: {//类似method
    SET_NAME(state, name) {
      state.name = name;
    }
  },
  actions: {//类似method
    set_name({ commit }, name) {
    	commit('SET_NAME', name)
  	}
  }

使用:dispatch提交触发actions里方法

this.$store.dispatch("set_name", 'xlt');

区别

  • commit方式是同步操作
  • dispatch方式是异步操作

总结

都可以修改state里的变量,并且是响应式的(能触发视图更新)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

© 版权声明
THE END
支持一下吧
点赞12 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容