Vue 3 中样式绑定的方式与 Vue 2 有一些变化。在 Vue 3 中,你可以使用v-bind指令来动态绑定样式。以下是一些示例:

对象语法:
<template>
  <div :style="{ color: textColor, fontSize: textSize + 'px' }">
    这是一个动态样式的例子
  </div>
</template>

<script>
export default {
  data() {
    return {
      textColor: 'red',
      textSize: 16
    };
  }
};
</script>

数组语法:
<template>
  <div :style="[baseStyles, dynamicStyles]">
    这是另一个动态样式的例子
  </div>
</template>

<script>
export default {
  data() {
    return {
      baseStyles: {
        color: 'blue',
        fontSize: '20px'
      },
      dynamicStyles: {
        backgroundColor: 'yellow',
        fontWeight: 'bold'
      }
    };
  }
};
</script>

使用计算属性:
<template>
  <div :style="computedStyles">
    这是计算属性的例子
  </div>
</template>

<script>
export default {
  data() {
    return {
      baseColor: 'green',
      baseFontSize: '18px'
    };
  },
  computed: {
    computedStyles() {
      return {
        color: this.baseColor,
        fontSize: this.baseFontSize
      };
    }
  }
};
</script>

以上是一些基本的示例,你可以根据具体情况动态调整样式。在 Vue 3 中,样式绑定的方式更加灵活,让你能够更方便地根据数据动态改变元素的样式。


转载请注明出处:http://www.zyzy.cn/article/detail/12982/Vue3