vue3制作导航切换,点击导航条中的导航项目,当前被点击的项目内容会显示在下方绿色方块中,并且当前被点击项目的背景颜色变成粉色
时间: 2024-10-28 11:09:53 浏览: 71
在Vue3中,你可以通过组件化的方式来创建这样的导航切换功能。通常的做法是使用`vuetify`、`vue-router`等库配合使用。以下是简单的步骤说明:
1. **安装依赖**:
- 安装`@vue/cli-plugin-vuex`和`vuetify`: `npm install @vue/cli-plugin-vuex vuetify`
- 如果还没有安装,还需安装`router`: `npm install vue-router`
2. **配置路由**:
- 创建一个`router/index.js`文件,设置路由和对应的视图组件,比如:
```js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/components/Home.vue'
// ...其他页面组件
const routes = [
{ path: '/', component: Home },
// 更多路由...
]
export default createRouter({
history: createWebHistory(), // 使用浏览器的history API
routes,
})
```
3. **创建导航组件**:
- 使用`vuetify`的`v-navigation-drawer`和`v-list`做导航栏,每个列表项对应一个路由:
```html
<v-navigation-drawer>
<v-list dense>
<v-list-item v-for="(route, index) in $router.options.routes" :key="index">
<v-list-item-title @click="$router.push(route.path)">
{{ route.name || route.path }}
</v-list-item-title>
<!-- 颜色变化效果 -->
<v-list-item-content v-bind:class="{ active: $route === route.path }" />
</v-list-item>
</v-list>
</v-navigation-drawer>
```
4. **处理状态**:
- 使用Vuex管理全局的状态,如当前选中的路由:
```js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
currentRoute: null,
},
mutations: {
setActiveRoute(state, routePath) {
state.currentRoute = routePath;
},
},
actions: {
setActiveRoute({ commit }, routePath) {
commit('setActiveRoute', routePath);
},
},
})
```
5. **更新导航项样式**:
- 当路由改变时,更新对应列表项的样式:
```js
// main.js 或 App.vue 中
import router from './router'
router.beforeEach((to, from, next) => {
store.commit('setActiveRoute', to.path);
next();
});
// 组件内获取样式
computed: {
isActive() {
return this.$store.state.currentRoute === this.route.path;
}
},
template: `
<v-list-item>
<!-- 其他内容... -->
<v-list-item-content class="active-color" :class="{ pink: isActive }"></v-list-item-content>
</v-list-item>
`,
// 其中`.pink`是自定义的CSS类,用于设置背景为粉色
style: `
.pink {
background-color: pink;
}
`,
```
这样当你点击导航项目时,相关的视图组件会在下方绿色方块中显示,同时当前项目的背景颜色变为粉色。
阅读全文
相关推荐















