当前位置: 代码网 > it编程>前端脚本>Vue.js > 前端vuex中dispatch的使用方法总结

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

2024年05月26日 Vue.js 我要评论
前言vuex中dispatch的用法!一、vuex和this.$store.dispatch是什么?vuex: vuex是专为vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件

前言

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使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com