说明
Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。功能包括:
嵌套路由映射
动态路由选择
模块化、基于组件的路由配置
路由参数、查询、通配符
展示由 Vue.js 的过渡系统提供的过渡效果
细致的导航控制
自动激活 CSS 类的链接
HTML5 history 模式或 hash 模式
可定制的滚动行为
URL 的正确编码
安装
pnpm add vue-router@4
配置
- 创建一个router文件夹,在文件夹下新建两个文件,分别是routes.ts和index.ts
- router.ts
export const constantRoute = [ { path: '/home/:id', component:()=> import('../vue-base/home.vue') }, { path: '/about', component:()=> import('../vue-base/about.vue') } ]
- index.ts
//通过vue-router插件实现模板路由配置 import {createRouter,createWebHashHistory} from 'vue-router' import {constantRoute} from './routes' //创建路由器 let router = createRouter({ history:createWebHashHistory(), routes:constantRoute }) export default router
- 在main.ts文件中注册插件
import router from './router'; app.use(router)
- 在app.vue设置出口
<script setup lang="ts"> </script> <template> <div> <router-view></router-view> </div> </template> <style scoped> </style>
使用
- 为了举例,创建了home.vue和about.vue两个文件
- home.vue
<template> <div> <h1>home</h1> <router-link to="/about">Go to About</router-link> </div> </template> <script setup lang="ts"> import { useRouter } from 'vue-router'; let router = useRouter() console.log(router.currentRoute.value.params) </script> <style scoped></style>
- about.vue
<template> <div> <h1>about</h1> <router-link to="/home">Go to Home</router-link> </div> </template> <script setup lang="ts"> </script> <style scoped></style>
效果图
vue-router(v4.0) 基础1
2024-03-18 23:12:03 40 阅读