vue 实现点击变颜色
Vue 实现点击变颜色的方法
在 Vue 中实现点击变颜色可以通过多种方式完成,以下是几种常见的方法:
使用 v-bind 和 v-on
通过 v-bind 动态绑定样式,结合 v-on 监听点击事件来改变颜色。

<template>
<div
@click="changeColor"
:style="{ backgroundColor: currentColor }"
style="width: 100px; height: 100px; cursor: pointer;"
>
点击我变色
</div>
</template>
<script>
export default {
data() {
return {
currentColor: 'red',
colors: ['red', 'blue', 'green', 'yellow']
};
},
methods: {
changeColor() {
const currentIndex = this.colors.indexOf(this.currentColor);
const nextIndex = (currentIndex + 1) % this.colors.length;
this.currentColor = this.colors[nextIndex];
}
}
};
</script>
使用 class 绑定
通过动态切换 class 来改变颜色。

<template>
<div
@click="toggleColor"
:class="{ 'red': isRed, 'blue': !isRed }"
style="width: 100px; height: 100px; cursor: pointer;"
>
点击我变色
</div>
</template>
<script>
export default {
data() {
return {
isRed: true
};
},
methods: {
toggleColor() {
this.isRed = !this.isRed;
}
}
};
</script>
<style>
.red {
background-color: red;
}
.blue {
background-color: blue;
}
</style>
使用计算属性
通过计算属性动态计算颜色。
<template>
<div
@click="toggleColor"
:style="{ backgroundColor: backgroundColor }"
style="width: 100px; height: 100px; cursor: pointer;"
>
点击我变色
</div>
</template>
<script>
export default {
data() {
return {
isRed: true
};
},
computed: {
backgroundColor() {
return this.isRed ? 'red' : 'blue';
}
},
methods: {
toggleColor() {
this.isRed = !this.isRed;
}
}
};
</script>
使用 Vue 3 的 Composition API
在 Vue 3 中可以使用 ref 和 reactive 来实现。
<template>
<div
@click="toggleColor"
:style="{ backgroundColor: color }"
style="width: 100px; height: 100px; cursor: pointer;"
>
点击我变色
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const color = ref('red');
const toggleColor = () => {
color.value = color.value === 'red' ? 'blue' : 'red';
};
return {
color,
toggleColor
};
}
};
</script>
注意事项
- 确保样式和逻辑分离,便于维护。
- 如果需要更多颜色切换,可以使用数组或对象存储颜色列表。
- 在 Vue 3 中,
ref和reactive提供了更灵活的状态管理方式。






