当前位置: 首页>后端>正文

vue3路由配置

1.安装vue-router:npm install vue-router@4

2.创建router文件夹,然后建一个index.ts文件

import { createRouter, createWebHistory } from 'vue-router'
import dashboard from '@/views/dashboard/index.vue'
import HelloWorld from '@/components/HelloWorld.vue'
import Login from '@/views/login/index.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: Login,
      name:'login'
    },
        {
            path:'/',
            redirect:'/login'  //默认显示
        },
    {
      path: '/helloworld',
      name: 'helloworld',
      component: HelloWorld
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('@/views/dashboard/index.vue')
    }
  ]
})
const isAuthenticated=sessionStorage.getItem('admin_token')
router.beforeEach(async (to, from) => {//路由守卫重定向
   if (
     // 检查用户是否已登录
     !isAuthenticated &&
     // ?? 避免无限重定向
     to.name !== 'login'
   ) {
     console.log(111)
     // 将用户重定向到登录页面
     location.href = '/login'
     return { name: 'Login' }
   }
 })
export default router

注意:一定要设置路由守卫,这样就可以默认登录页为首页

2.在main.ts里面

import router from '@/router'
app.use(router)

3.App.vue页面代码

<template>
  <router-view></router-view>
</template>

https://www.xamrdz.com/backend/3p51940916.html

相关文章: