Vue3 如何在同级路由中导航
时间: 2024-02-05 18:14:19 浏览: 19
Vue3 中可以使用 `<router-link>` 组件或 `router.push()` 方法来在同级路由中进行导航。
使用 `<router-link>` 组件:
```html
<template>
<div>
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</div>
</template>
```
使用 `router.push()` 方法:
```js
// 在组件中
this.$router.push('/foo')
this.$router.push('/bar')
// 在普通的 JavaScript 中
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
})
router.push('/foo')
router.push('/bar')
```
注意:如果你当前已经在 `/foo` 路径下,再使用 `router.push('/foo')` 并不会触发路由变化,因为路由并没有发生变化。如果需要强制触发路由变化,可以使用 `router.replace('/foo')` 或 `router.go(0)`。