前端vuex中dispatch的使用

前端 0

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、vuex和this.$store.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)    });  });}

总结

Vuex是专为Vue.js应用程序开发的状态管理模式。
this.$store.dispatch是用于触发vuex中action的方法。

也许您对下面的内容还感兴趣: