Vue3跳转路由并刷新菜单
时间: 2024-05-12 10:13:06 浏览: 144
在Vue3中,您可以使用Vue Router来实现路由跳转和刷新菜单的功能。以下是一个简单的例子:
首先,在您的组件中使用`router-link`标签来创建一个链接,例如:
```html
<router-link to="/dashboard">Dashboard</router-link>
```
然后,在您的Vue Router实例中,定义一个路由对象,例如:
```javascript
import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from './views/Dashboard.vue'
const routes = [
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
最后,在您的菜单组件中,可以使用`router.currentRoute.value.path`来获取当前路由路径,并根据需要进行刷新菜单。例如:
```html
<template>
<div>
<ul>
<li :class="{ active: isActive('/dashboard') }">
<router-link to="/dashboard">Dashboard</router-link>
</li>
<li :class="{ active: isActive('/users') }">
<router-link to="/users">Users</router-link>
</li>
</ul>
</div>
</template>
<script>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
const isActive = (path) => {
return computed(() => route.currentRoute.value.path === path)
}
return {
isActive
}
}
}
</script>
```
这样,在用户点击菜单链接时,Vue Router会自动处理路由跳转,并且您的菜单组件也会自动刷新以反映当前路由状态。
阅读全文