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']
};
},
methods: {
changeColor() {
const nextColor = this.colors[(this.colors.indexOf(this.currentColor) + 1) % this.colors.length];
this.currentColor = nextColor;
}
}
};
</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="boxStyle"
style="width: 100px; height: 100px; cursor: pointer;"
></div>
</template>
<script>
export default {
data() {
return {
isRed: true
};
},
computed: {
boxStyle() {
return {
backgroundColor: 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>
以上方法均可实现点击元素改变颜色的效果,具体选择哪种方式取决于项目需求和个人偏好。







