安装

参考文档: https://github.com/vuejs/vue-router-next
npm install vue-router@4

配置

  1. import { createRouter, createWebHistory } from "vue-router";
  2. const routes = [
  3. { path: "/", name: "home", component: Home },
  4. { path: "/login", name: "login", component: Login },
  5. { path: "/columnDetail/:id", name: "columnDetail", component: ColumnDetail },
  6. ];
  7. const router = createRouter({
  8. history: createWebHistory(),
  9. routes,
  10. });
  11. export default router;

在main.js中安装

  1. createApp(App).use(Router).mount("#app");

使用

使用router-link跳转

  1. # 1.基础跳转
  2. <router-link class="btn btn-outline-light my-2" to="/columnDetail">
  3. 注册
  4. </router-link>
  5. # 2.1 使用param传参
  6. <router-link
  7. class="btn btn-outline-light my-2"
  8. :to="{ name: 'column', params: { id: 123 } }"
  9. >
  10. 注册
  11. </router-link>
  12. # 2.2 使用query传参
  13. <router-link
  14. class="btn btn-outline-light my-2"
  15. :to="{ name: 'column', query: { id: 123 } }"
  16. >
  17. 注册
  18. </router-link>
  19. # 3.使用模板字符串传参
  20. <router-link
  21. class="btn btn-outline-light my-2"
  22. :to="`/columnDetail/${456}`"
  23. >
  24. 注册
  25. </router-link>

查看当前路由详细参数

  1. import { useRoute } from "vue-router";
  2. const route = useRoute();
  3. console.log("route", route);

使用router进行跳转

  1. import { useRouter } from "vue-router";
  2. // 普通跳转
  3. const toColumnDetail = () => {
  4. router.push("/columnDetail/121212");
  5. };
  6. // 传参
  7. const toColumnDetail = () => {
  8. router.push({
  9. name: "columnDetail",
  10. params: { id: "222222" },
  11. });
  12. };