深入理解 Vuex 中的this.$store.dispatch方法

简介: 深入理解 Vuex 中的this.$store.dispatch方法

基础知识

在 Vuex 中,this.$store.dispatch 方法用于向 store 发起一个mutation 事件。

Mutation 是改变 Vuex 存储状态的唯一方法。

以下是 this.$store.dispatch 方法的基本使用示例:

1.首先,确保你在 Vue 组件中已经引入了 Vuex:

import Vuex from 'vuex';

2.然后,在你的组件中使用 this.$store.dispatch 方法来触发一个Mutation:

// 假设你有一个名为 increment 的 Mutation
this.$store.dispatch('increment');

3.在你的 Vuex store 中定义这个 Mutation:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++;
    }
  }
});

通过以上步骤,你可以使用 this.$store.dispatch 方法来触发 increment Mutation,从而递增 count 的值。

需要注意的是,this.$store.dispatch 方法需要一个字符串作为参数,这个字符串对应于你在 Vuex store 中定义的 Mutation 的名称。

另外,还可以通过传递一个对象作为第二个参数来传递 Mutation 的参数:

this.$store.dispatch('increment', 5);

这将把 5 作为 increment Mutation 的参数传递给它。

知识储备

在 Vuex 中,需要使用 commit 方法来触发mutations 里的方法

mutations用于改变 Vuex 存储状态的唯一方式

以下是一个示例:

  1. 首先,确保你在 Vue 组件中已经引入了 Vuex:
import Vuex from 'vuex';
  1. 然后,在你的组件中使用 this.$store.commit 方法来触发一个 Mutation:
// 假设你有一个名为 SET_TOKEN 的 Mutation
this.$store.commit('SET_TOKEN', tokenV);
  1. 在这个示例中,SET_TOKEN 是你在 Vuex store 中定义的 Mutation 的名称,tokenV 是你要传递给Mutation 的参数。
  2. 最后,在你的 Vuex store 中定义这个 Mutation:
const store = new Vuex.Store({
  state: {
    // 存储状态的地方
  },
  mutations: {
    // 定义 Mutation
    SET_TOKEN (state, token) {
      state.token = token;
    }
  }
});

通过以上三个步骤,你可以使用 this.$store.commit 方法来触发 SET_TOKEN Mutation,从而在 store 中成功存储 tokenV

需要注意的是,在使用 commit 方法时,确保传递正确的 Mutation 名称和参数。如果 Mutation 名称或参数不正确,或者没有在 store 中定义相应的 Mutation,那么存储操作可能会失败。

案例解析

传送门

main.js

new Vue({
  router,
  store,
  i18n,
  render: h => h(App),
}).$mount('#app')

store/index.js

在store/modules文件夹里的user.js,声明user并释放出来。

const user = {
  state: {
    token: '',
    roles: null,
    isMasterAccount:true,
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token ="Bearer " +token 
    },
  },
  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.account, userInfo.password).then(x => {
          if(x.status==200){
            const tokenV = x.data.token.tokenValue
            commit('SET_TOKEN', tokenV)
            document.cookie=`AuthInfo=Bearer ${tokenV};path:/`;
            token="Bearer "+tokenV;
            //setToken("Bearer " +token)
            resolve();
          }
        }).catch(error => {
          console.log("登录失败")
          reject(error)
        })
      })
    },
  }
}
export default user

注:必须要用commit(‘SET_TOKEN’, tokenV)调用mutations里的方法,才能在store存储成功。

handleLogin() {
   this.loading = true
    this.$store.dispatch('Login', this.loginForm).then(() => {
           this.$router.push({
               path: '/manage/merchant/account'
           }); //登录成功之后重定向到首页
           this.loading = false
           // this.$router.push({ path: this.redirect || '/' })
       }).catch(() => {
           this.loading = false
       })
     }

this.$store.dispatch(‘Login’, this.loginForm)来调取store里的user.js的login方法,从而要更新。

相关文章
|
5月前
|
前端开发 JavaScript BI
轻松搞定vue3+Pinia-2-修改state-patch-actions
轻松搞定vue3+Pinia-2-修改state-patch-actions
109 0
|
7月前
|
JavaScript 测试技术 调度
使用 Ngrx ActionSubject 监听 Dispatched NgRx Actions
使用 Ngrx ActionSubject 监听 Dispatched NgRx Actions
50 0
|
JavaScript
在Redux中使用useSelector和useDispatch
在redux中使用useSelector和useDispacth来获取数据
87 0
|
前端开发 API
patch使用
+ put:对所有资源进行更新 + patch:对部分资源进行更新 put使用方法和post相同,但是put是幂等的。
|
前端开发 Java 开发者
Dispatch 设计| 学习笔记
快速学习 Dispatch 设计。
Dispatch 设计| 学习笔记
|
开发工具 git
生成patch
生成patch
|
监控
Dispatch Source 应用
Dispatch Source 源是一个偏底层的函数集合,使用时CPU负荷非常小,尽量不占资源,开发过程中大多是配合定时器使用。
163 0
|
JavaScript
说说 element 组件库 broadcast 与 dispatch
说说 element 组件库 broadcast 与 dispatch
228 0
|
前端开发
获取this.$store.dispatch的返回值
获取this.$store.dispatch的返回值
1005 0
NgRx store.dispatch方法的单步调试
NgRx store.dispatch方法的单步调试
207 0
NgRx store.dispatch方法的单步调试