如何将token存到vuex中

步骤流程


具体实现

在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

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值