vue3使用vue-router@4

468 阅读2分钟

温馨提示:此文章在有vue2基础上书写,可以先看vue2里面的router文章

完整代码示例代码

注意版本信息: "vue": "^3.0.0", "vue-router": "^4.0.12"

vue-router原理传送门

配置映射关系 router/index.js

使用了 compositionAPI 需要引入

和vue2不同的是:匹配任意路由从 * 变成了正则

import { createRouter, createWebHistory } from "vue-router";
import Home from "../pages/Home.vue";
// import About from "../pages/About.vue";// 配置映射关系
const routes = [
  // 路由重定向
  { path: "/", redirect: "/home" },
  {
    path: "/home",
    component: Home,
    name: "home",
    meta: { info: '2022年1月19日 星期三'},
    children: [
      // 重定向不能省略父路径
      {path: "", redirect: "/home/msg"},
      {path: "msg", component: () => import("../views/home/HomeMsg.vue")},
      {path: "shop", component: () => import("../views/home/HomeShop.vue")}
    ]
  },
  // 路由懒加载,防止首次加载过重
  // 在import函数里面写上该注释,能够指定webpack打包文件的名字
  {
    path: "/about",
    component: () =>
      import(/* webpackChunkName: "about-chunk" */ "../pages/About.vue"),
  },
  // 动态路由
  {
    path: "/user/:username/id/:id",
    component: () => import("../pages/User.vue")
  },
  // 当路径没有在映射关系中没定义,则在这里任意匹配
  {
    path: "/:pathMatch(.*)",
    component: () => import("../pages/NotFound.vue")
  }
];
​
// 创建一个路由对象
const router = createRouter({
  routes,
  history: createWebHistory(),
  // linkActiveClass 指定激活时routerview的css类
  // linkExactActiveClass
});
​
// 导出实例
export default router;

main.js文件中使用router

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'const app =  createApp(App)
app.use(router)
app.mount("#app")

RouterLink 组件

<router-link></router-link> 用来跳转路由的组件;to 属性存放该组件跳转的路由路径

    <!-- 不写active-class 会默认加上 router-link-active这个类 -->
    <router-link to="/about" active-class="code-active">About</router-link> |
    <router-link to="/home" active-class="code-active">Home</router-link> |
    <router-link to="/user/kobe/id/123" active-class="code-active"
      >User</router-link
    >|
    <router-link to="/addRoute" active-class="code-active">newRoute</router-link>

同样,RouterLink是组件也有用组件所有的属性及作用域

    <router-link to="/" v-slot="props">
      <!-- routerLink 也拥有很多属性 -->
      <!-- props:href 跳转的链接 -->
      <!-- props:route对象 -->
      <!-- props:navigate 导航函数 -->
      <!-- props:isActive 是否处于活跃状态 -->
      <!-- props:isExactActive 是否当前是精确的活跃状态 -->
      <button @click="getRouterLinkProps(props)">{{ props.href }}</button>
    </router-link>

RouterView组件

和一样,同样有组件

  <!-- <router-view/> -->
  <!-- routerView 同样拥有组件属性 -->
  <!-- Component: 渲染的组件 -->
  <!-- route:解析出来的标准化路由对象 -->

router-view完全体

    <!-- routerView 搭配过渡transition和缓存keepalive的使用 -->
  <router-view v-slot="props">
    <!-- <transition name="routerView"> -->
      <keep-alive>
        <component :is="props.Component"></component>
      </keep-alive>
    <!-- </transition> -->
  </router-view>

vue-router自带的方法

// 引入路由方法
import { useRouter } from "vue-router";
setup() {
    // 实例化路由对象
    const router = useRouter();
    console.log(router);
    .....
    }
​

image-20220210141245312.png

添加路由对象

    // 添加顶层路由对象路由对象
    const newRoute = { path:"/addRoute", component: () => import("./views/otherPage/AddRoute.vue"), name: "addRoute" }
    router.addRoute(newRoute)
​
    // 添加子路由对象
    // 第一个参数是父路由对象的name
    const newChildRoute = { path: "newChild", component: () => import("./views/otherPage/AddChild")}
    router.addRoute("addRoute", newChildRoute)

删除路由对象

删除路由三种方式

  1. 添加一个name同名的路由,替换掉
  2. 通过removeRoute方法,传入路由的名称
  3. 通过addRoute返回值回调

路由跳转

      // 1. 跳转到指定路由
      router.push("/404");
      // 2. 跳转到指定路由,并携带query
      // router.push({
      //   path: "/about",
      //   query: {
      //     username: "why",
      //     id: 18
      //   }
      // })
​
      // 3. 替换路由
      // router.replace("/user/why/id/10086")
​
      // 正数前进,负数后退
      // router.go(-1)

全局前置路由导航守卫

和之前的守卫有点不同

// 导航守卫
let counter = 0
// to: Route对象(即将跳转到的路由对象)
// from: Route对象(出发路由对象)
// next(router@4版本,不推荐使用)
/**
 * return返回值
 * 1. false: 不进行导航跳转
 * 2. undefined或不写:进行默认导航
 * 3. 字符串(路径):跳转到目的路径
 * 4. 对象:router.push({})
 */
router.beforeEach((to, from) => {
  // if(counter > 5) return false
  // if (counter > 3) return "/about"console.log(`进行了${++ counter}次路由跳转`);
})