前端vuex中dispatch的使用方法总结

前言

Vuex中dispatch的用法!

一、vuex和this.$store.dispatch是什么?

Vuex: Vuex是专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

this.$store.dispatch: this.$store.dispatch是用于触发vuex中action的方法。

二、使用方法

#基础用法
this.$store.dispatch('actionName');

#实际案例(登录)

this.$store.dispatch('LoginByUsername', this.loginForm).then(() => {
  this.$router.push({ path: '/' }); //登录成功之后重定向到首页
}).catch(err => {
  this.$message.error(err); //登录失败提示错误
});

action:

LoginByUsername({ commit }, userInfo) {
  const username = userInfo.username.trim()
  return new Promise((resolve, reject) => {
    loginByUsername(username, userInfo.password).then(response => {
      const data = response.data
      Cookies.set('Token', response.data.token) //登录成功后将token存储在cookie之中
      commit('SET_TOKEN', data.token)
      resolve()
    }).catch(error => {
      reject(error)
    });
  });
}

附:dispatch和commit的作用和区别

相同点:二者最终都是用来提交mutation来更改state的值的

不同点:dispacth用于异步操作修改state,commit用于同步操作来修改state

总结

Vuex是专为Vue.js应用程序开发的状态管理模式。

this.$store.dispatch是用于触发vuex中action的方法。

到此这篇关于前端vuex中dispatch的使用方法的文章就介绍到这了,更多相关vuex中dispatch使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章: