vue3如何实现官网头部选中状态切换
时间: 2023-07-20 11:26:00 浏览: 54
官网头部选中状态切换是通过Vue Router的路由切换来实现的。具体实现步骤如下:
1. 在Vue Router中定义路由信息,包括路由路径和对应的组件。
```
const routes = [
{ path: '/', component: Home },
{ path: '/guide', component: Guide },
{ path: '/api', component: API },
{ path: '/examples', component: Examples },
{ path: '/blog', component: Blog },
{ path: '/community', component: Community },
{ path: '/about', component: About },
];
```
2. 在头部组件中监听路由变化,并根据当前路由路径来改变选中状态。
```
<template>
<div class="header">
<a :class="{ active: $route.path === '/' }" href="/">Home</a>
<a :class="{ active: $route.path === '/guide' }" href="/guide">Guide</a>
<a :class="{ active: $route.path === '/api' }" href="/api">API</a>
<a :class="{ active: $route.path === '/examples' }" href="/examples">Examples</a>
<a :class="{ active: $route.path === '/blog' }" href="/blog">Blog</a>
<a :class="{ active: $route.path === '/community' }" href="/community">Community</a>
<a :class="{ active: $route.path === '/about' }" href="/about">About</a>
</div>
</template>
<script>
export default {
mounted() {
this.$router.afterEach((to) => {
this.currentPath = to.path;
});
},
};
</script>
```
3. 在CSS中定义选中状态样式。
```
.active {
background-color: #42b983;
color: #fff;
}
```