vue实现当前元素高亮
vue实现当前元素高亮的方法
通过动态绑定class或style实现高亮效果,结合v-for和事件处理完成交互逻辑。
模板部分
<template>
<div>
<div
v-for="(item, index) in list"
:key="index"
@click="selectItem(index)"
:class="{ 'active': currentIndex === index }"
>
{{ item }}
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
list: ['选项1', '选项2', '选项3'],
currentIndex: -1
}
},
methods: {
selectItem(index) {
this.currentIndex = index
}
}
}
</script>
样式部分
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用CSS变量动态控制高亮
通过Vue的响应式特性动态修改CSS变量值,实现更灵活的高亮控制。
<template>
<div
v-for="(item, index) in items"
:key="index"
@click="activeIndex = index"
:style="activeIndex === index ? activeStyle : ''"
>
{{ item }}
</div>
</template>
<script>
export default {
data() {
return {
items: ['元素A', '元素B', '元素C'],
activeIndex: null,
activeStyle: {
backgroundColor: '#ffeb3b',
border: '2px solid #ff9800'
}
}
}
}
</script>
使用计算属性管理高亮状态
当高亮逻辑较复杂时,可使用计算属性返回高亮元素的索引。
computed: {
highlightedItem() {
return this.items.findIndex(item => item.status === 'active')
}
}
第三方库实现方案
使用vue-directive自定义指令实现高亮功能,增强代码复用性。
Vue.directive('highlight', {
bind(el, binding) {
el.addEventListener('click', () => {
document.querySelectorAll('[v-highlight]').forEach(item => {
item.style.backgroundColor = ''
})
el.style.backgroundColor = binding.value
})
}
})
注意事项
- 高亮样式应具有明显的视觉对比度
- 移动端需考虑
:active伪类与点击状态的配合 - 大量元素高亮时建议使用虚拟滚动优化性能
- 高亮状态可配合Vuex进行全局管理







