vue实现列表高亮
Vue 实现列表高亮的方法
动态绑定 class 实现高亮
通过 v-bind:class 动态绑定类名,根据条件判断是否添加高亮样式。在模板中使用 :class 绑定一个对象,对象的键为类名,值为布尔表达式。
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="{ 'highlight': index === activeIndex }"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
使用计算属性管理高亮状态
对于更复杂的高亮逻辑,可以使用计算属性返回类名对象或数组。计算属性能够根据响应式数据自动更新高亮状态。
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="getHighlightClass(index)"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1
}
},
computed: {
getHighlightClass() {
return (index) => ({
'highlight': index === this.activeIndex,
'bold-text': index % 2 === 0
})
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
}
.bold-text {
font-weight: bold;
}
</style>
使用数组语法绑定多个类名
通过数组语法可以同时绑定多个类名,结合对象语法实现更灵活的高亮控制。
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="['list-item', { 'highlight': index === activeIndex }]"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<style>
.list-item {
padding: 8px;
margin: 4px;
}
.highlight {
background-color: #ffeb3b;
}
</style>
使用内联样式实现高亮
通过 v-bind:style 动态绑定样式对象,直接修改元素的样式属性实现高亮效果。
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:style="index === activeIndex ? highlightStyle : {}"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1,
highlightStyle: {
backgroundColor: 'yellow',
fontWeight: 'bold'
}
}
}
}
</script>
高亮当前路由匹配的菜单项
在导航菜单中高亮当前路由匹配的菜单项,可以使用 vue-router 的 router-link 和 active-class 属性。
<template>
<ul>
<router-link
v-for="(item, index) in menuItems"
:key="index"
:to="item.path"
active-class="highlight"
tag="li"
>
{{ item.title }}
</router-link>
</ul>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ title: 'Home', path: '/' },
{ title: 'About', path: '/about' },
{ title: 'Contact', path: '/contact' }
]
}
}
}
</script>
<style>
.highlight {
background-color: #4CAF50;
color: white;
}
</style>
以上方法可以根据具体需求选择使用,动态绑定类名是最常用的实现方式,适合大多数高亮场景。







