vue实现点击不同颜色
Vue 实现点击切换颜色的方法
在 Vue 中可以通过数据绑定和事件处理实现点击切换颜色的功能。以下是几种常见实现方式:
使用 v-bind 和 v-on 指令
<template>
<div
class="color-box"
:style="{ backgroundColor: currentColor }"
@click="changeColor"
>点击我切换颜色</div>
</template>
<script>
export default {
data() {
return {
colors: ['red', 'green', 'blue', 'yellow'],
currentColor: 'red',
currentIndex: 0
}
},
methods: {
changeColor() {
this.currentIndex = (this.currentIndex + 1) % this.colors.length
this.currentColor = this.colors[this.currentIndex]
}
}
}
</script>
<style>
.color-box {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
</style>
使用动态 class 绑定
<template>
<div
class="color-box"
:class="currentColor"
@click="changeColor"
>点击我切换颜色</div>
</template>
<script>
export default {
data() {
return {
colors: ['red', 'green', 'blue', 'yellow'],
currentColor: 'red',
currentIndex: 0
}
},
methods: {
changeColor() {
this.currentIndex = (this.currentIndex + 1) % this.colors.length
this.currentColor = this.colors[this.currentIndex]
}
}
}
</script>
<style>
.color-box {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
</style>
使用计算属性实现随机颜色
<template>
<div
class="color-box"
:style="{ backgroundColor: randomColor }"
@click="changeColor"
>点击我切换随机颜色</div>
</template>
<script>
export default {
data() {
return {
colorChanged: false
}
},
computed: {
randomColor() {
const letters = '0123456789ABCDEF'
let color = '#'
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)]
}
return color
}
},
methods: {
changeColor() {
this.colorChanged = !this.colorChanged
}
}
}
</script>
使用 Vue 3 Composition API
<template>
<div
class="color-box"
:style="{ backgroundColor: currentColor }"
@click="changeColor"
>点击我切换颜色</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const colors = ['red', 'green', 'blue', 'yellow']
const currentIndex = ref(0)
const currentColor = ref(colors[0])
const changeColor = () => {
currentIndex.value = (currentIndex.value + 1) % colors.length
currentColor.value = colors[currentIndex.value]
}
return {
currentColor,
changeColor
}
}
}
</script>
这些方法都可以实现点击切换颜色的效果,根据具体需求选择最适合的实现方式。第一种方法使用内联样式,第二种使用CSS类,第三种生成随机颜色,第四种展示了Vue 3的Composition API实现。







