vue实现点击变颜色
Vue 实现点击变颜色的方法
使用 v-bind 和 v-on 动态绑定样式
通过 v-bind 动态绑定 style 或 class,结合 v-on 监听点击事件,切换颜色状态。
<template>
<div
:style="{ color: textColor }"
@click="changeColor"
>
点击我改变颜色
</div>
</template>
<script>
export default {
data() {
return {
textColor: 'black'
}
},
methods: {
changeColor() {
this.textColor = this.textColor === 'black' ? 'red' : 'black';
}
}
}
</script>
使用 v-bind:class 切换类名
通过切换类名实现颜色变化,适合需要多种样式切换的场景。
<template>
<div
:class="{ 'active': isActive }"
@click="toggleColor"
>
点击我切换颜色
</div>
</template>
<script>
export default {
data() {
return {
isActive: false
}
},
methods: {
toggleColor() {
this.isActive = !this.isActive;
}
}
}
</script>
<style>
.active {
color: blue;
}
</style>
使用计算属性动态生成样式
通过计算属性动态生成样式对象,适合复杂样式逻辑。
<template>
<div
:style="textStyle"
@click="toggleStyle"
>
点击我动态改变样式
</div>
</template>
<script>
export default {
data() {
return {
isStyled: false
}
},
computed: {
textStyle() {
return {
color: this.isStyled ? 'green' : 'black',
fontWeight: this.isStyled ? 'bold' : 'normal'
};
}
},
methods: {
toggleStyle() {
this.isStyled = !this.isStyled;
}
}
}
</script>
使用 Vue 3 的 Composition API
在 Vue 3 中,可以使用 ref 和 reactive 实现类似功能。
<template>
<div
:style="{ color: color }"
@click="changeColor"
>
点击我改变颜色(Vue 3)
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const color = ref('black');
const changeColor = () => {
color.value = color.value === 'black' ? 'purple' : 'black';
};
return { color, changeColor };
}
}
</script>
注意事项
- 样式绑定可以直接使用内联样式(
style)或类名(class),根据需求选择。 - 动态绑定的值可以是固定值、计算属性或方法返回的结果。
- Vue 3 的 Composition API 提供了更灵活的响应式状态管理方式。







