vue实现多选选中变色
Vue实现多选选中变色的方法
使用v-for和v-bind动态绑定样式
通过v-for渲染列表,结合v-bind动态绑定class或style实现选中状态切换。数据驱动视图变化是Vue的核心特性。
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
@click="toggleSelect(index)"
:class="{ 'selected': selectedItems.includes(index) }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ text: '选项1' },
{ text: '选项2' },
{ text: '选项3' }
],
selectedItems: []
}
},
methods: {
toggleSelect(index) {
const idx = this.selectedItems.indexOf(index)
if (idx > -1) {
this.selectedItems.splice(idx, 1)
} else {
this.selectedItems.push(index)
}
}
}
}
</script>
<style>
.selected {
background-color: #42b983;
color: white;
}
</style>
使用计算属性管理选中状态
计算属性可以更优雅地处理复杂的选择逻辑,特别是当选中状态需要依赖多个条件时。
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
@click="toggleSelect(index)"
:style="getItemStyle(index)"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ text: '选项A' },
{ text: '选项B' },
{ text: '选项C' }
],
selectedIndices: []
}
},
computed: {
getItemStyle() {
return (index) => ({
backgroundColor: this.selectedIndices.includes(index) ? '#ff7043' : '',
color: this.selectedIndices.includes(index) ? 'white' : 'black'
})
}
},
methods: {
toggleSelect(index) {
const idx = this.selectedIndices.indexOf(index)
idx > -1
? this.selectedIndices.splice(idx, 1)
: this.selectedIndices.push(index)
}
}
}
</script>
使用Vuex管理全局选中状态
对于大型应用,可以使用Vuex集中管理选中状态,实现跨组件共享。
// store.js
export default new Vuex.Store({
state: {
selectedItems: []
},
mutations: {
TOGGLE_SELECT(state, index) {
const idx = state.selectedItems.indexOf(index)
idx > -1
? state.selectedItems.splice(idx, 1)
: state.selectedItems.push(index)
}
}
})
<!-- 组件中使用 -->
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
@click="toggleSelect(index)"
:class="{ 'active': $store.state.selectedItems.includes(index) }"
>
{{ item.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [...] // 项目数据
}
},
methods: {
toggleSelect(index) {
this.$store.commit('TOGGLE_SELECT', index)
}
}
}
</script>
使用第三方UI库实现
Element UI等库提供了现成的多选组件,可以快速实现类似功能。
<template>
<el-checkbox-group v-model="selectedOptions">
<el-checkbox
v-for="option in options"
:label="option.value"
:key="option.value"
>
{{ option.label }}
</el-checkbox>
</el-checkbox-group>
</template>
<script>
export default {
data() {
return {
options: [
{ value: '1', label: '选项1' },
{ value: '2', label: '选项2' }
],
selectedOptions: []
}
}
}
</script>






