详解vuex中的this.$store.dispatch方法
vuex中的this.$store.dispatch方法
main.js
new Vue({
el:'#app',
router,
store,
render:h=>h(APP)
})
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from '.modules/user'
import getters from '.getters'
import permission from './modules/permission'
Vue.use(Vuex)
const store=new Vuex.Store({
modules:{
permission,
app,
user
},
getters
})
export default store
在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方法,从而要更新。
vuex 中dispatch 和 commit 的用法和区别
dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)
commit:同步操作,写法:this.$store.commit('mutations方法名',值)
到此这篇关于vuex中的this.$store.dispatch方法的文章就介绍到这了,更多相关vuex中this.$store.dispatch方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Vue2实现Office文档(docx、xlsx、pdf)在线预览功能
在现代的Web应用开发中,实现Office文档(如docx、xlsx、pdf)的在线预览功能是一个常见的需求,下面小编就来和大家详细介绍一下如何使用vue2实现这一功能吧2025-05-05
Vue.js表单标签中的单选按钮、复选按钮和下拉列表的取值问题
这篇文章主要介绍了Vue.js表单标签中的单选按钮、复选按钮和下拉列表的取值问题,非常不错,具有参考借鉴价值,需要的朋友可以参考下2017-11-11
解决element-ui中Popconfirm气泡确认框的事件不生效问题
这篇文章主要介绍了解决element-ui中Popconfirm气泡确认框的事件不生效问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-07-07
如何解决Element-ui的el-table固定列后出现的表格错位问题
这篇文章主要介绍了如何解决Element-ui的el-table固定列后出现的表格错位问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-09-09


最新评论