vue实现列表点击变色
实现列表点击变色的方法
在Vue中实现列表点击变色可以通过动态绑定类名或样式的方式完成。以下是两种常见的实现方式:
使用动态类名绑定
通过v-bind:class或简写:class动态切换类名,结合CSS实现颜色变化:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="{ 'active': activeIndex === index }"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用内联样式绑定
通过v-bind:style或简写:style直接修改元素样式:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:style="{ backgroundColor: activeIndex === index ? '#42b983' : 'transparent' }"
@click="activeIndex = index"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
activeIndex: -1
}
}
}
</script>
多选模式实现
如果需要支持多选(点击多个项目变色),可以使用数组存储选中状态:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="{ 'active': activeItems.includes(index) }"
@click="toggleActive(index)"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
activeItems: []
}
},
methods: {
toggleActive(index) {
const idx = this.activeItems.indexOf(index)
if (idx > -1) {
this.activeItems.splice(idx, 1)
} else {
this.activeItems.push(index)
}
}
}
}
</script>
使用计算属性优化
对于更复杂的逻辑,可以使用计算属性处理选中状态:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
:class="getItemClass(index)"
@click="toggleActive(index)"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
activeItems: []
}
},
computed: {
getItemClass() {
return (index) => ({
'active': this.activeItems.includes(index),
'disabled': this.activeItems.length >= 2 && !this.activeItems.includes(index)
})
}
},
methods: {
toggleActive(index) {
const idx = this.activeItems.indexOf(index)
if (idx > -1) {
this.activeItems.splice(idx, 1)
} else if (this.activeItems.length < 2) {
this.activeItems.push(index)
}
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
.disabled {
opacity: 0.5;
pointer-events: none;
}
</style>
以上方法可以根据实际需求选择使用,动态类名绑定适合样式复杂的情况,内联样式适合简单样式修改,多选模式则扩展了基础功能。







