vue实现点击变色
Vue 实现点击变色方法
方法一:使用 v-bind 和 v-on
通过 v-bind 动态绑定样式,结合 v-on 监听点击事件,切换颜色状态。
<template>
<div
@click="toggleColor"
:style="{ backgroundColor: activeColor }"
>
点击切换颜色
</div>
</template>
<script>
export default {
data() {
return {
activeColor: 'red',
colors: ['red', 'blue', 'green']
}
},
methods: {
toggleColor() {
const currentIndex = this.colors.indexOf(this.activeColor);
const nextIndex = (currentIndex + 1) % this.colors.length;
this.activeColor = this.colors[nextIndex];
}
}
}
</script>
方法二:使用 class 绑定
通过动态切换 CSS 类名实现颜色变化,适合需要复杂样式的情况。
<template>
<div
@click="isActive = !isActive"
:class="{ 'active': isActive }"
>
点击切换颜色
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
}
}
}
</script>
<style>
.active {
background-color: yellow;
}
</style>
方法三:使用计算属性
当颜色逻辑较复杂时,可通过计算属性动态返回样式对象。
<template>
<div
@click="toggleState"
:style="boxStyle"
>
点击切换颜色
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
}
},
computed: {
boxStyle() {
return {
backgroundColor: this.isActive ? 'purple' : 'gray',
transition: 'all 0.3s ease'
}
}
},
methods: {
toggleState() {
this.isActive = !this.isActive
}
}
}
</script>
注意事项
- 颜色值可以使用十六进制、RGB 或颜色名称
- 添加 CSS
transition属性可实现平滑过渡效果 - 对于列表项点击变色,需使用唯一标识区分不同元素的状态







