小程序P176 14.登录与支付-登录-获取登录的Token并存储到vuex中(接上一个)
③在 my-login 组件中,把 vuex 中的 updateToken 方法映射到当前组件中使用:
methods: {
// 1. 使用 mapMutations 辅助方法,把 m_user 模块中的 updateToken 方法映射到当前组件中使用
...mapMutations('m_user', ['updateUserInfo', 'updateToken'])
// 省略其它代码...
// 调用登录接口,换取永久的 token
async getToken(info) {
// 调用微信登录接口
const [err, res] = await uni.login().catch(err => err)
// 判断是否 uni.login() 调用失败
if (err || res.errMsg !== 'login:ok') return uni.$showError('登录失败!')
// 准备参数对象
const query = {
code: res.code,
encryptedData: info.encryptedData,
iv: info.iv,
rawData: info.rawData,
signature: info.signature
}
// 换取 token
const { data: loginResult } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
//if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败!')
if (loginResult.meta.status !== 200) return this.updateToken(res.code)
// 2. 更新 vuex 中的 token
this.updateToken(loginResult.message.token)
}
}