预实现场景: 在微信公众号里,用户首次登录需要使用手机号加验证码,当登录成功后和手机号绑定,下次登录就不用输入手机号验证码了。
刚开始是这样写的:因为没有出口,所以会陷入死循环。
// 路由守卫
router.beforeEach((to, from, next) => {
if (location.href.indexOf('code=') === -1) {
// 初次进入请求code
getCodeByRedirect()
} else {
// 从服务端查询手机号是否绑定过微信
const searchCode = location.search.split('&')[0]
const code = searchCode.replace(/^\?code=/g, '')
let useCode = code
window.axios.post('查询url', { wxcode: useCode }).then(res => {
if (res.code === 200) {
if (!res.no_bind) {
// 绑定过
setToken(res.Mcc_token)
setBuyer(res.Mcc_buyer)
next()
} else {
next('/login')
}
} else {
next('/login')
}
})
}
})
文字解释: 1 .先去获取微信code,传参用。
需改写:
router.beforeEach((to, from, next) => {
if (location.href.indexOf('code=') === -1) {
// 初次进入请求code
getCodeByRedirect()
} else {
const searchCode = location.search.split('&')[0]
const code = searchCode.replace(/^\?code=/g, '')
let useCode = code
// 从服务端查询手机号是否绑定过微信
window.axios.post('查询url', { wx_mcc_home_code: useCode }).then(res => {
if (res.code === 200) {
if (!res.no_bind) {
// 绑定过
setToken(res.Mcc_token)
setBuyer(res.Mcc_buyer)
next()
} else {
to.name === 'login' ? next() : next('/login')
}
} else {
to.name === 'login' ? next() : next('/login')
}
})
}
})
需要加判断,给他一个出口