0
点赞
收藏
分享

微信扫一扫

vue3-路由遇到的问题

在Vue 3中,使用Vue Router来管理应用程序的导航和路由。下面是Vue Router的一些常见使用方法:

    • 通过npm或yarn安装Vue Router:npm install vue-routeryarn add vue-router
    • 在主文件(通常是main.js)中导入Vue Router并创建一个实例:

    import { createApp } from 'vue'
    import router from './router' //这个地方表示引入router文件夹下的index.ts 导入Vue Router到main.ts
    import store from './store'
    import 'element-plus/dist/index.css'
    import ElementPlus from 'element-plus'
    import zhCn from "element-plus/es/locale/lang/zh-cn"
    import "lib-flexible/flexible.js" 
    
    createApp(App).use(ElementPlus, {
        locale: zhCn,
      }).use(store).use(router).mount('#app')  //这个use(router)进行挂载
    

    • 在views中创建index.ts文件

    //导入创建路由对象方法和hash 模式路径方法
    import { createRouter, createWebHashHistory } from 'vue-router
    //创建路由表
    const routes = [
    {
        path: '/',
        name: 'Home',
        component: () => import('../views/Home.vue'),
    },
    {
        path: '/about/:id',
        name: 'About',
        component: () => import('../views/About.vue')
    },
    ]
    //创建路由对象
    const router = createRouter({
      history: createWebHashHistory(),//hash模式路径
      routes//路由表
    })
    //导出路由对象
    export default router

    • 如何使用路由

    //to属性指定路由路径
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
    //router-view为路由视图
    <router-view/>

    • 路由守卫(可以使用权限控制)

    路由守卫: Vue Router提供了一系列的路由守卫用于在路由跳转时执行特定的逻辑。你可以使用beforeEachbeforeResolveafterEach等方法来定义路由守卫:

    router.beforeEach((to,from,next)=>{
      //to是到达的路由
      //from是开源的路由
      //next跳转路由的函数
      const adminPaths=['/postList']
      const user = JSON.parse(localStorage.getItem("user")||'{}')
      if(user.roleName!=='admin' && adminPaths.includes(to.path)){
        next('/403'); //没有路径访问权限
      }else next()
    })

    • 匹配所有路径

    常规参数只会匹配被 / 分隔的 URL 片段中的字符。如果想匹配任意路径,vue2中我们可以使用通配符 (*):,vue3中用 "/:pathMatch(.*)"

    {     
      // 匹配所有路径  vue2使用*   vue3使用/:pathMatch(.*)    
      path:"*",//vue2
      path: "/:pathMatch(.*)", 
      path: '/stu:pathMatch(.*)',//可以以什么开头    
      name: "404",     
      component: () => import('../views/404.vue')  
    }

    举个例子

     {
        path: '/:pathMatch(.*)',//vue3
        name: '404',
        component: () => import( '../views/404.vue')//这是另外一种导入路由所需模块的方式
      }

    当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分:

    //404.vue
    {{$route.params.pathMatch}}
    //返回地址名


    举报

    相关推荐

    0 条评论