vue style怎么根据值动态变化举个例子
假设需要根据用户的选择动态改变颜色,可以使用以下代码:
<template>
<div :style="{ color: textColor }">
{{ message }}
</div>
<button @click="changeColor('red')">红色</button>
<button @click="changeColor('green')">绿色</button>
</template>
<script>
export default {
data() {
return {
message: 'Hello World!',
textColor: 'black'
}
},
methods: {
changeColor(color) {
this.textColor = color
}
}
}
</script>
在这个例子中,使用了:style绑定了一个对象,对象的key是color,value是textColor,textColor是一个变量,初始值为black。当用户点击按钮时,调用changeColor方法,将textColor的值改变为red或green,从而实现了动态改变颜色的效果。
原文地址: http://www.cveoy.top/t/topic/ZYJ 著作权归作者所有。请勿转载和采集!