vue实现li高亮效果
实现方法
在Vue中实现li高亮效果可以通过多种方式完成,以下是几种常见的方法:
使用动态class绑定
通过v-bind:class或简写:class动态绑定class,根据条件切换高亮样式。
<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
:class="{ 'highlight': activeIndex === index }"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1
};
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
使用内联样式绑定
通过v-bind:style或简写:style动态绑定内联样式。
<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
:style="activeIndex === index ? highlightStyle : {}"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1,
highlightStyle: {
backgroundColor: 'yellow',
fontWeight: 'bold'
}
};
}
};
</script>
使用计算属性
通过计算属性返回高亮样式或class,适合复杂逻辑。
<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
:class="getClass(index)"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1
};
},
methods: {
getClass(index) {
return {
highlight: this.activeIndex === index
};
}
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
使用Vuex管理状态
如果项目中使用Vuex,可以将高亮状态集中管理。

<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
:class="{ 'highlight': $store.state.activeIndex === index }"
@click="$store.commit('setActiveIndex', index)"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3']
};
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
注意事项
- 确保
v-for中的:key唯一且稳定。 - 高亮样式可以根据需求自定义,如颜色、边框等。
- 如果列表数据动态变化,需确保
activeIndex同步更新。
以上方法均能实现li高亮效果,选择适合项目需求的方式即可。






