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