- 未登录不能去&已登录不能去(路由前置守卫)
- 想去某界面,未登录情况下跳转到登录界面,登录后跳转到该界面(登录函数中判断+redirect)
-
未登录不能去&已登录不能去(路由前置守卫)
router.beforeEach(async (to, from, next) => {let token = store.state.user.token;let name = store.state.user.userInfo.name;//用户已登录if (token) {//登录过了 不能去登录或注册页面if (to.path == '/register' || to.path == '/login') {next('/home')} else {//是否有用户信息if (name) {next()} else {try {//获取用户信息await store.dispatch('getUserInfo');next()} catch (error) {//token过期store.dispatch('userLogout');next('/login')}}}} else { //用户未登录//未登录:不能去交易相关、不能去支付相关【pay|paysuccess】、不能去个人中心//未登录去上面这些路由-----登录let toPath = to.path;if (toPath.includes('/trade') || toPath.includes('/pay') || toPath.includes('/center')) {//login页面 点击登录按钮时 根据是否有redirect来判断跳转页面next('/login?redirect=' + toPath)} else {next()}}})
想去某界面,未登录情况下跳转到登录界面
路由前置守卫 next(‘/login?redirect=’ + toPath) 参考1
methods:{async userLogin(){try {let { phone, password } =this;//登录phone&&password && await this.$store.dispatch('userLogin', { phone, password })//登录的路由组件:看路由当中是否包含query参数,//有:调到query参数指定路由,没有:调到homelet toPath = this.$route.query.redirect || '/home'this.$router.push(toPath)} catch (error) {alert(error.message)}}}
只能从【购物车】跳转到【交易】(路由独享守卫)
{path:'/trade',component:()=>import('@/pages/Trade'),/* 跳转到交易界面,只能从购物车界面进入 */beforeEnter(to,from,next){//判断从哪来,是则放行,不是则进入到购物车if(from.path == '/shopcart'){next()}else{next('/shopcart')}},},
