vue实现li高亮效果
Vue实现li高亮效果的方法
方法一:使用动态class绑定
通过v-bind:class或简写:class动态切换高亮样式,结合v-for渲染列表:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="{ 'highlight': activeIndex === index }"
@click="activeIndex = index"
>
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ text: 'Item 1' },
{ text: 'Item 2' },
{ text: 'Item 3' }
],
activeIndex: -1
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
方法二:使用内联样式
通过:style直接绑定样式对象,适合需要动态计算样式的场景:

<li
v-for="(item, index) in items"
:key="index"
:style="{
backgroundColor: activeId === item.id ? '#ffeb3b' : '',
color: activeId === item.id ? '#000' : ''
}"
@click="activeId = item.id"
>
{{ item.name }}
</li>
方法三:使用计算属性 当高亮逻辑较复杂时,可通过计算属性返回样式或class:

computed: {
liClasses() {
return this.items.map(item => ({
'active-item': this.selectedItem === item.id,
'disabled': item.disabled
}))
}
}
方法四:组件化封装 对于复用场景,可封装为可配置的组件:
<highlight-list
:items="dataList"
highlight-class="custom-highlight"
@item-click="handleClick"
/>
注意事项
- 高亮状态应存储在组件data或Vuex中
- 移动端建议添加
:active伪类提升点击反馈 - 性能优化:大数据列表使用
v-virtual-scroll避免DOM过度渲染






