1. 未登录不能去&已登录不能去(路由前置守卫)
  2. 想去某界面,未登录情况下跳转到登录界面,登录后跳转到该界面(登录函数中判断+redirect)
  3. 只能从【购物车界面】跳转到【交易界面】(路由独享守卫)

    未登录不能去&已登录不能去(路由前置守卫)

    1. router.beforeEach(async (to, from, next) => {
    2. let token = store.state.user.token;
    3. let name = store.state.user.userInfo.name;
    4. //用户已登录
    5. if (token) {
    6. //登录过了 不能去登录或注册页面
    7. if (to.path == '/register' || to.path == '/login') {
    8. next('/home')
    9. } else {
    10. //是否有用户信息
    11. if (name) {
    12. next()
    13. } else {
    14. try {
    15. //获取用户信息
    16. await store.dispatch('getUserInfo');
    17. next()
    18. } catch (error) {
    19. //token过期
    20. store.dispatch('userLogout');
    21. next('/login')
    22. }
    23. }
    24. }
    25. } else { //用户未登录
    26. //未登录:不能去交易相关、不能去支付相关【pay|paysuccess】、不能去个人中心
    27. //未登录去上面这些路由-----登录
    28. let toPath = to.path;
    29. if (toPath.includes('/trade') || toPath.includes('/pay') || toPath.includes('/center')) {
    30. //login页面 点击登录按钮时 根据是否有redirect来判断跳转页面
    31. next('/login?redirect=' + toPath)
    32. } else {
    33. next()
    34. }
    35. }
    36. })

    想去某界面,未登录情况下跳转到登录界面

    路由前置守卫 next(‘/login?redirect=’ + toPath) 参考1

  1. methods:{
  2. async userLogin(){
  3. try {
  4. let { phone, password } =this;
  5. //登录
  6. phone&&password && await this.$store.dispatch('userLogin', { phone, password })
  7. //登录的路由组件:看路由当中是否包含query参数,
  8. //有:调到query参数指定路由,没有:调到home
  9. let toPath = this.$route.query.redirect || '/home'
  10. this.$router.push(toPath)
  11. } catch (error) {
  12. alert(error.message)
  13. }
  14. }
  15. }

只能从【购物车】跳转到【交易】(路由独享守卫)

  1. {
  2. path:'/trade',
  3. component:()=>import('@/pages/Trade'),
  4. /* 跳转到交易界面,只能从购物车界面进入 */
  5. beforeEnter(to,from,next){
  6. //判断从哪来,是则放行,不是则进入到购物车
  7. if(from.path == '/shopcart'){
  8. next()
  9. }else{
  10. next('/shopcart')
  11. }
  12. },
  13. },