需求场景
在微信小程序开发中,点击结算页面结算按钮之前进行判断是否登录,若未登录则跳转到登录页面进行登录操作,登录后页面自动返回到结算页面。
实现过程
vuex中代码如下:
// user.js
state: () => ({
// 存放对应页面信息 { openType, from }
redirectInfo: null
})
mutations: {
// 修改redirectInfo
updateRedirectInfo(state, info) {
state.redirectInfo = info
}
}
结算按钮所在页面
// settle.vue
// 导入vuex所需辅助函数
import { mapState, mapMutations, mapGetters } from 'vuex'
methods: {
...mapMutations('m_user', ['updateRedirectInfo']),
}
// 提交订单
async submitOrder() {
//省略其他代码
if (true) {
uni.switchTab({
// 跳转登录页面
url: '/pages/my/my',
success: () => {
this.updateRedirectInfo({
// 若是跳转tabbar页面则用 `switchTab`
openType: 'navigateTo',
// 结算页面放在分包中
from: '/subpkg/settle/settle'
})
}
})
}
}
登录组件
// 获取token处理函数
getToken() {
// ...省略其他代码
// 成功登录获取到token后,调用页面跳转函数
this.navigateBack()
}
navigateBack() {
// 判断redirectInfo !== null 且跳转方式为navigateTo
if(this.redirectInfo !== null && this.redirectInfo.opentype === 'navigateTo') {
uni.navigateTo({
// 导航完成以后,把vuex中的redirectInfo重置为null
complete() {
this.updateRedirectInfo(null)
}
})
}
}