Vue3——404、重定向以及导航守卫

Vue3跳转404页面

在路由配置中添加一个名为“NotFound”的路由,用于处理404页面:

import NotFound from '@/view/NotFound/404.vue'
  {
    path: '/:pathMatch(.*)',
    //访问主页的时候 重定向到index页面
    redirect: '/404',
  },
    {
    path: '/404',
    name: '/404',
    component: NotFound
  },

其中,pathMatch(.*)*表示匹配所有路径,component指定了404页面的组件。

创建路由实例:

const router = createRouter({ 
    history: createWebHistory(), routes 
})

路由重定向

Vue2的重定向

  {
    path: "/",
    redirect: "/Login",
  },
  {
    path: "/Login",
    name: "Login",
    component: Login,
  }

Vue3的重定向

  {
    path: '/',
    redirect: '/index',
    meta: {
      title: '首页',
      isShow: true,
    }
  },
    {
    path: '/list',
    name: '模型列表',
    component: Model,
    children: [{
      path: '/list',
      name: '首页',
      component: () => import('@/view/3DModel/List.vue'),
      meta: { title: '首页', isShow: true, },
    },
    {
      path: '/list/initmodel',
      name: '模型详情',
      component: () => import('@/view/3DModel/InitModel.vue'),
      meta: { title: '模型详情', keepAlive: true, isShow: true, },
    },
    {
      path: '/getmodel/management',
      name: 'management',
      component: () => import('@/view/3DModel/Management.vue'),
      meta: { title: '模型管理', isShow: true, },
    },
    {
      path: '/getmodel/category',
      name: '分类管理',
      component: () => import('@/view/3DModel/Category.vue'),
      meta: {
        title: '分类管理',
        isShow: true,
      }
    },
    ]
  },

创建导航守卫

导航守卫:用于在路由切换时进行拦截和控制。它可以在路由切换前、路由切换后、路由切换取消时等不同的阶段进行拦截和处理,从而实现一些特定的功能,比如路由权限控制、路由跳转记录、路由切换动画等。Vue中的导航守卫包括全局前置守卫、全局后置钩子、路由独享守卫、组件内的守卫等。开发者可以根据具体的需求选择不同的导航守卫进行使用。

在路由守卫中添加一个全局前置守卫,用于检查用户是否已登录:
如果找到token那么就允许放行,否则停留在原地,也就是所谓的login.vue页面中

router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next()
  } else {
    const token = window.sessionStorage.getItem('token')
    if (!token) {
      next('/login')
    } else {
      next()
    }
  }
})

当然也可以将token存在Pinia中再进行判断

router.beforeEach((to, from, next) => { 
    if (to.meta.requiresAuth && !store.state.token) { 
        next({ name: 'Login' }) 
    } else { 
        next() 
    } 
})

原文链接:https://juejin.cn/post/7244818202214973499 作者:SouthernWind

(0)
上一篇 2023年6月16日 上午11:01
下一篇 2023年6月16日 上午11:12

相关推荐

发表回复

登录后才能评论