步骤流程
具体实现
在login/login.vue中调用actions方法
async doLogin () {
try {
await this.$store.dispatch('userLogin', this.user) //调用actions方法
this.$toast.success('登录成功')
} catch (err) {
console.log(err)
this.$toast.fail('登录失败')
}
}
在store/index.js中发送ajax请求并获取设置token值
state: {
tokenInfo: {} // 定义tokenInfo变量
},
mutations: {
mSetTokenInfo (state, initTokenInfo) {
state.tokenInfo = initTokenInfo //修改tokenInfo的值
}
},
actions: {
async userLogin (context, userInfo) {
try {
const res = await login(userInfo) //发送ajax请求
context.commit('mSetTokenInfo', res.data.data) //调用mutation方法并传递token值
} catch (err) {
throw new Error(err) //抛出错误
}
}
},
总结
async...await...使用
1.index.js中使用async...await
是为了让userLogin方法等待ajax请求结束再执行后面的同步代码
2.login.vue中使用async...await
是为了让doLogin方法等待dispatch调用的userLogin执行完毕再执行, 如果没有await, doLogin方法不会等dispatch执行完, 而是会在dispatch方法等待ajax请求时继续执行后面的同步 代码, 会导致后面的代码先执行, 所以需要async...await...
index.js中使用try...catch抛出错误原因
如果index.js中不在catch中抛出错误,那么login.vue中的try会认为内部代码执行完毕没有错误而不会触发catch