vue实现列表高亮
Vue 列表高亮实现方法
动态类绑定
通过 v-bind:class 或简写 :class 实现条件高亮
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="{ 'highlight': item.isActive }"
@click="toggleHighlight(index)"
>
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ text: 'Item 1', isActive: false },
{ text: 'Item 2', isActive: false }
]
}
},
methods: {
toggleHighlight(index) {
this.list.forEach((item, i) => {
item.isActive = i === index
})
}
}
}
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
行内样式绑定
使用 :style 直接绑定样式对象
<li
v-for="(item, index) in list"
:key="index"
:style="item.isActive ? activeStyle : {}"
>
{{ item.text }}
</li>
<script>
export default {
data() {
return {
activeStyle: {
backgroundColor: '#ffeb3b',
fontWeight: 'bold'
}
}
}
}
</script>
多选高亮实现
支持同时高亮多个列表项
methods: {
toggleHighlight(index) {
this.list[index].isActive = !this.list[index].isActive
}
}
高亮动画效果
添加过渡动画增强用户体验
.highlight {
transition: all 0.3s ease;
transform: scale(1.02);
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}
基于路由的高亮
根据当前路由高亮对应导航项
computed: {
activeIndex() {
return this.list.findIndex(item =>
item.path === this.$route.path
)
}
}






