假设需要根据用户的选择动态改变颜色,可以使用以下代码:

<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是textColortextColor是一个变量,初始值为black。当用户点击按钮时,调用changeColor方法,将textColor的值改变为redgreen,从而实现了动态改变颜色的效果。


原文地址: http://www.cveoy.top/t/topic/ZYJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录