vue实现点击高亮
实现点击高亮的基本思路
在Vue中实现点击高亮效果,可以通过动态绑定CSS类或内联样式来实现。核心是利用Vue的响应式数据和事件处理机制,记录当前被点击的元素并应用高亮样式。
方法一:使用动态类绑定
通过v-bind:class动态切换高亮类,结合点击事件修改当前选中项的索引或ID。
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
@click="selectedIndex = index"
:class="{ 'highlight': selectedIndex === index }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [{ text: 'Item 1' }, { text: 'Item 2' }, { text: 'Item 3' }],
selectedIndex: -1
};
}
};
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
方法二:使用内联样式
通过v-bind:style直接绑定样式对象,动态计算样式属性。
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
@click="selectedIndex = index"
:style="selectedIndex === index ? highlightStyle : {}"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [{ text: 'Item 1' }, { text: 'Item 2' }, { text: 'Item 3' }],
selectedIndex: -1,
highlightStyle: {
backgroundColor: 'yellow',
fontWeight: 'bold'
}
};
}
};
</script>
方法三:基于组件的高亮实现
如果是自定义组件,可以通过props传递高亮状态,并在组件内部处理样式。
<template>
<div>
<CustomItem
v-for="(item, index) in items"
:key="index"
:text="item.text"
:isHighlighted="selectedIndex === index"
@click="selectedIndex = index"
/>
</div>
</template>
<script>
import CustomItem from './CustomItem.vue';
export default {
components: { CustomItem },
data() {
return {
items: [{ text: 'Item 1' }, { text: 'Item 2' }, { text: 'Item 3' }],
selectedIndex: -1
};
}
};
</script>
方法四:多选高亮
若需支持多选高亮,可以用数组记录选中状态。
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
@click="toggleHighlight(index)"
:class="{ 'highlight': highlightedIndices.includes(index) }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [{ text: 'Item 1' }, { text: 'Item 2' }, { text: 'Item 3' }],
highlightedIndices: []
};
},
methods: {
toggleHighlight(index) {
const i = this.highlightedIndices.indexOf(index);
if (i === -1) {
this.highlightedIndices.push(index);
} else {
this.highlightedIndices.splice(i, 1);
}
}
}
};
</script>
样式优化建议
高亮样式可根据需求调整,例如添加过渡动画:

.highlight {
background-color: yellow;
transition: background-color 0.3s ease;
}
注意事项
- 确保
v-for的:key唯一,避免渲染问题。 - 高亮逻辑可复用为Mixin或Composable(Vue 3)。
- 移动端考虑添加
:active伪类增强点击反馈。






