vue实现点击高亮效果
使用动态类绑定实现高亮
在Vue中可以通过v-bind:class或简写:class动态绑定CSS类来实现点击高亮效果。定义一个响应式数据存储当前选中项,点击时更新该数据。
<template>
<div>
<div
v-for="item in items"
:key="item.id"
:class="{ 'active': activeItem === item.id }"
@click="activeItem = item.id"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeItem: null,
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
}
}
</script>
<style>
.active {
background-color: yellow;
}
</style>
使用内联样式绑定
通过v-bind:style直接动态修改元素的样式属性,适合简单的高亮效果。

<template>
<div>
<div
v-for="item in items"
:key="item.id"
:style="{ backgroundColor: activeItem === item.id ? 'yellow' : '' }"
@click="activeItem = item.id"
>
{{ item.text }}
</div>
</div>
</template>
多选高亮实现
需要高亮多个元素时,可以使用数组或对象存储选中状态。

<template>
<div>
<div
v-for="item in items"
:key="item.id"
:class="{ 'active': selectedItems.includes(item.id) }"
@click="toggleSelection(item.id)"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedItems: [],
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
},
methods: {
toggleSelection(id) {
const index = this.selectedItems.indexOf(id)
if (index === -1) {
this.selectedItems.push(id)
} else {
this.selectedItems.splice(index, 1)
}
}
}
}
</script>
使用计算属性优化
对于复杂的高亮逻辑,可以使用计算属性返回类名或样式对象。
<template>
<div>
<div
v-for="item in items"
:key="item.id"
:class="getItemClass(item.id)"
@click="activeItem = item.id"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeItem: null,
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
},
computed: {
getItemClass() {
return (id) => ({
'active': this.activeItem === id,
'important': id === 1 // 额外条件示例
})
}
}
}
</script>
组件化实现
将高亮逻辑封装为可复用组件,通过props和events与父组件通信。
<!-- HighlightableItem.vue -->
<template>
<div
:class="{ 'active': isActive }"
@click="$emit('click')"
>
<slot></slot>
</div>
</template>
<script>
export default {
props: {
isActive: Boolean
}
}
</script>
<!-- ParentComponent.vue -->
<template>
<div>
<highlightable-item
v-for="item in items"
:key="item.id"
:is-active="activeItem === item.id"
@click="activeItem = item.id"
>
{{ item.text }}
</highlightable-item>
</div>
</template>






