Vue Router
基本用法
路由链接和视图显示
路由链接 <RouterLink>
<RouterLink>
用于导航到不同的路由。以下是几种常见的使用方式:
1 2 3 4 5 6 7 8
| <RouterLink to="/home" active-class="active">首页</RouterLink>
<RouterLink :to="{name: 'xinwen'}" active-class="active">新闻</RouterLink>
<RouterLink :to="{path: '/about'}" active-class="active">关于</RouterLink>
|
显示路由加载区域 <RouterView>
<RouterView>
是路由匹配到的组件将要渲染的地方。
1
| <RouterView></RouterView>
|
路由配置文件 index.ts
在 index.ts
文件中配置路由规则:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import { createRouter, createWebHistory } from 'vue-router'; import Home from './views/Home.vue'; import News from './views/News.vue'; import Detail from './views/Detail.vue';
const router = createRouter({ history: createWebHistory(), routes: [ { name: 'zhuye', path: '/home', component: Home }, { name: 'xinwen', path: '/news', component: News, children: [ { path: 'detail', component: Detail } ] } ] });
export default router;
|
路由传参
Query 参数传递
通过 query
参数进行传参:
1 2 3 4 5 6 7 8 9 10 11 12
| <RouterLink :to="{ name: 'xiang', query: { id: news.id, title: news.title, content: news.content } }" > 新闻详情 </RouterLink>
|
接收参数
方法1:使用 props
在路由配置中设置 props
函数来接收参数:
1 2 3 4 5 6 7
| { path: '/xiang', component: Xiang, props(route) { return route.query; } }
|
在组件内使用 defineProps
:
1
| defineProps(['id', 'title', 'content']);
|
方法2:直接使用 $route
1 2 3
| <li>编号:{{ $route.query.id }}</li> <li>标题:{{ $route.query.title }}</li> <li>内容:{{ $route.query.content }}</li>
|
或者使用组合式API:
1 2 3 4 5 6 7 8 9 10
| import { useRoute } from 'vue-router'; import { toRefs } from '@vueuse/core';
export default { setup() { const route = useRoute(); const { query } = toRefs(route); return { query }; } };
|
编程式路由导航
可以使用 router.push()
、router.replace()
等方法进行编程式导航:
1 2 3 4 5 6 7 8
| router.replace({ name: 'xiang', query: { id: news.id, title: news.title, content: news.content } });
|
路由重定向
在路由配置中添加重定向规则:
1 2 3 4
| { path: '/', redirect: '/home' }
|