vue3中如何实现路由导航跳转
在 Vue 3 里,$router
是 Vue Router 提供的实例,可用于路由导航。使用 $router
进行路径跳转时,路径的写法会依据路由的配置与导航方式而有所不同。以下为你详细介绍几种常见的情况:
1. 绝对路径跳转
绝对路径跳转意味着直接使用完整的路由路径来跳转。
代码示例
<template>
<div>
<!-- 点击按钮触发跳转 -->
<button @click="goToHome">跳转到首页</button>
<button @click="goToAbout">跳转到关于页</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
// 获取路由实例
const router = useRouter();
// 跳转到首页的方法
const goToHome = () => {
router.push('/');
};
// 跳转到关于页的方法
const goToAbout = () => {
router.push('/about');
};
</script>
2. 命名路由跳转
若在路由配置里给路由设置了名称,就可以使用命名路由来跳转,这种方式会让代码更具可读性与可维护性。
路由配置示例
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
代码示例
<template>
<div>
<!-- 点击按钮触发跳转 -->
<button @click="goToHome">跳转到首页</button>
<button @click="goToAbout">跳转到关于页</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
// 获取路由实例
const router = useRouter();
// 跳转到首页的方法
const goToHome = () => {
router.push({ name: 'Home' });
};
// 跳转到关于页的方法
const goToAbout = () => {
router.push({ name: 'About' });
};
</script>
3. 带参数的路由跳转
在某些情况下,你可能需要在跳转时传递参数,参数可以是查询参数(query)或者路径参数(params)。
查询参数跳转
<template>
<div>
<!-- 点击按钮触发跳转 -->
<button @click="goToUser">跳转到用户页</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
// 获取路由实例
const router = useRouter();
// 跳转到用户页并传递查询参数的方法
const goToUser = () => {
router.push({
path: '/user',
query: { id: 123 }
});
};
</script>
路径参数跳转
// 路由配置
const routes = [
{
path: '/user/:id',
name: 'User',
component: () => import('./views/User.vue')
}
];
<template>
<div>
<!-- 点击按钮触发跳转 -->
<button @click="goToUser">跳转到用户页</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router';
// 获取路由实例
const router = useRouter();
// 跳转到用户页并传递路径参数的方法
const goToUser = () => {
router.push({
name: 'User',
params: { id: 123 }
});
};
</script>
以上便是在 Vue 3 里使用 $router
进行路径跳转时常见的路径写法,你可以依据实际需求来选择合适的方式。