vue实现菜单点击
Vue 实现菜单点击功能
在 Vue 中实现菜单点击功能可以通过以下方式完成:
使用 v-on 或 @click 绑定点击事件
通过 Vue 的指令 v-on:click 或简写 @click 可以直接在模板中绑定点击事件。

<template>
<div>
<ul>
<li v-for="item in menuItems" :key="item.id" @click="handleMenuClick(item)">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ id: 1, name: '首页' },
{ id: 2, name: '产品' },
{ id: 3, name: '关于我们' }
]
}
},
methods: {
handleMenuClick(item) {
console.log('点击了菜单:', item.name)
// 执行其他逻辑,如路由跳转或更新状态
}
}
}
</script>
动态高亮当前选中菜单
通过绑定 class 或 style 动态控制当前选中菜单的高亮状态。
<template>
<div>
<ul>
<li
v-for="item in menuItems"
:key="item.id"
@click="activeItem = item.id"
:class="{ 'active': activeItem === item.id }"
>
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
activeItem: 1,
menuItems: [
{ id: 1, name: '首页' },
{ id: 2, name: '产品' },
{ id: 3, name: '关于我们' }
]
}
}
}
</script>
<style>
.active {
color: #42b983;
font-weight: bold;
}
</style>
结合 Vue Router 实现路由跳转
如果菜单用于导航,可以直接结合 Vue Router 实现路由跳转。

<template>
<div>
<ul>
<li
v-for="item in menuItems"
:key="item.path"
@click="$router.push(item.path)"
:class="{ 'active': $route.path === item.path }"
>
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ path: '/', name: '首页' },
{ path: '/products', name: '产品' },
{ path: '/about', name: '关于我们' }
]
}
}
}
</script>
使用事件修饰符优化点击行为
Vue 提供事件修饰符(如 .prevent、.stop)可以简化事件处理逻辑。
<template>
<div>
<ul>
<li v-for="item in menuItems" :key="item.id">
<a href="#" @click.prevent="handleMenuClick(item)">
{{ item.name }}
</a>
</li>
</ul>
</div>
</template>
封装可复用的菜单组件
将菜单逻辑封装为组件,提高复用性。
<!-- Menu.vue -->
<template>
<ul>
<li
v-for="item in items"
:key="item.id"
@click="$emit('menu-click', item)"
:class="{ 'active': activeId === item.id }"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
props: {
items: Array,
activeId: [String, Number]
}
}
</script>
<!-- ParentComponent.vue -->
<template>
<Menu
:items="menuItems"
:active-id="activeItem"
@menu-click="handleMenuClick"
/>
</template>
<script>
import Menu from './Menu.vue'
export default {
components: { Menu },
data() {
return {
activeItem: 1,
menuItems: [
{ id: 1, name: '首页' },
{ id: 2, name: '产品' },
{ id: 3, name: '关于我们' }
]
}
},
methods: {
handleMenuClick(item) {
this.activeItem = item.id
// 其他逻辑
}
}
}
</script>
以上方法可以根据实际需求选择或组合使用,灵活实现菜单点击功能。






