vue-router4.x的使用配置静态和动态路由

240 阅读1分钟

安装vue-router

  1. 下载vue-router包
npm i vue-router //yarn add vue-router
  1. 项目中使用

    静态路由

    创建文件src/router/index.ts文件和src/view/login.vue文件

    //index.ts
    
    import { createRouter, createWebHashHistory } from 'vue-router'
    const routes = [{path:'/',component:()=>import('@/view/login.vue')},{path:'/home',component:()=>import('@/view/home.vue')}] 
    
    // 创建路由实例并传递 `routes` 配置
    const router = createRouter({
    // 使用 hash 模式。
    history: createWebHashHistory(),
    routes, // `routes: routes` 的缩写
    })
    
    export default router
    
    
    
    //login.vue
    <template>login</template>
    

    在main.ts中挂载vue-router

      import router from "vue-router"
      create(App).use(router).mount("#app")
    

    运行项目,在根路径下加/login,页面应该就能加载成功。有一个坑,view下文件夹名称和文件名称不能一样,比如view/login/login.vue就会报错,或者不显示。

    动态路由

    动态路由的本质就是在静态路由的基础上,通过从后台拿到的数据,对静态路由routes数组进行进行追加{}。 比如说已经封装了一个接口,并且已经定义调用这个接口的函数getNavData().

    //路由拦截
    router.beforeEach(async(to,from,next)=>{
      //发送请求,收获数据
      let res=await getNavData();
      //将数据数据缓存到mainstore仓库,调用setNav方法,防止不停的切换路由,不停的发起请求,数据库压力大。
      mainStore().setNav(res.data);
      //转换数组类型,符合静态路由格式
      const navData=fn(res.data);
      //追加到router中
      router.addRoute(navData);
    
    }}
    
    
      //定义转换类型
      function fn(res){
      //过滤
      let homeRoutes=route.filter(v=>v.path=='/home')[0];
      //定义home路由下的children属性
      homeRoutes.children=[];
      //通过接口提供的res.data数据,遍历相关数据推送到home路由的子路由中
      res.forEach(item=>{homeRoutes.children.push({
      path:item.path,
      name:item.name,
      //因为数据是动态绑定所以是``而不是''。更改变化的地址,用${}包裹
      component:()=>import(`../view/home/${item.component}/index.vue`)
      })
      })
      }