Vue实现列表选择变色
Vue实现列表选择变色的方法
使用v-bind动态绑定class
通过v-bind:class结合条件判断,为选中的列表项添加特定样式类。当点击列表项时,更新当前选中项的索引或ID,触发样式变化。
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
@click="selectedIndex = index"
:class="{ 'active': selectedIndex === index }"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
selectedIndex: null
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用v-bind动态绑定style
直接通过v-bind:style动态修改内联样式,适合需要更灵活样式控制的场景。
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
@click="selectedIndex = index"
:style="selectedIndex === index ? activeStyle : {}"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
selectedIndex: null,
activeStyle: {
backgroundColor: '#42b983',
color: 'white'
}
}
}
}
</script>
使用计算属性管理选中状态
对于复杂逻辑,可以使用计算属性返回样式对象或类名数组,保持模板简洁。
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
@click="selectedIndex = index"
:class="getItemClass(index)"
>
{{ item }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3'],
selectedIndex: null
}
},
methods: {
getItemClass(index) {
return {
'active': this.selectedIndex === index,
'disabled': index === 0 // 示例:额外条件
}
}
}
}
</script>
<style>
.active {
background-color: #42b983;
}
.disabled {
opacity: 0.5;
}
</style>
使用Vuex管理全局状态
当选中状态需要跨组件共享时,可以通过Vuex管理当前选中项。
// store.js
export default new Vuex.Store({
state: {
selectedItemId: null
},
mutations: {
setSelectedItem(state, id) {
state.selectedItemId = id
}
}
})
<template>
<ul>
<li
v-for="item in list"
:key="item.id"
@click="$store.commit('setSelectedItem', item.id)"
:class="{ 'active': $store.state.selectedItemId === item.id }"
>
{{ item.name }}
</li>
</ul>
</template>
注意事项
- 确保为列表项添加唯一的
key属性,帮助Vue高效更新DOM - 复杂项目建议将样式逻辑抽离到CSS文件中维护
- 移动端项目可以考虑添加
:active伪类提升点击反馈体验







