vue 3 第二十七章:样式(动态class、动态style)

文章目录


在 Vue 中,我们可以使用动态绑定语法来动态地添加类名或样式。本章将介绍 Vue 3 中如何使用动态绑定语法来动态地添加类名或样式。

动态 class

在 Vue 中,我们可以使用 :classv-bind:class 指令来动态地添加类名。例如,下面的例子中,我们可以根据 isActive 的值动态地为元素添加 active 类:

<template>
  <div>
    <h1 :class="{ active: isActive }">Dynamic Class</h1>
    <button @click="isActive = !isActive">切换</button>
  </div>
</template>

<script setup lang="ts">
import {
      
       ref } from "vue";
const isActive = ref(false);
</script>

<style lang="scss" scoped>
.active {
      
      
  color: red;
}
</style>

在上面的例子中,:class="{ active: isActive }" 的意思是,当 isActive 的值为 true 时,为元素添加 active 类。

除了使用对象语法以外,我们还可以使用数组语法来动态地添加类名。例如,下面的例子中,我们可以根据 isActiveisHighlighted 的值动态地为元素添加类:

<template>
  <div :class="[isActive && 'active', isHighlighted && 'highlighted']">
    <h1>Dynamic Class</h1>
  </div>
</template>

<script setup lang="ts">
import {
      
       ref } from "vue";
const isActive = ref(true);
const isHighlighted = ref(false);
</script>

在上面的例子中,:class="[isActive && 'active', isHighlighted && 'highlighted']" 的意思是,当 isActive 的值为 true 时,为元素添加 active 类;当 isHighlighted 的值为 true 时,为元素添加 highlighted 类。

动态 style

在 Vue 中,我们可以使用 :stylev-bind:style 指令来动态地添加样式。例如,下面的例子中,我们可以根据 color 的值动态地为元素设置颜色:

<template>
  <div :style="{ color }">
    <h1>Dynamic Style</h1>
  </div>
</template>

<script setup lang="ts">
import {
      
       ref } from "vue";
const color = ref("red");
</script>

在上面的例子中,:style="{ color }" 的意思是,为元素设置颜色,颜色的值为 color 变量的值。

除了使用对象语法以外,我们还可以使用数组语法来动态地添加样式。例如,下面的例子中,我们可以根据 fontSizelineHeight 的值动态地为元素设置样式:

<template>
  <div
    :style="[
      fontSize && { 'font-size': fontSize },
      lineHeight && { 'line-height': lineHeight },
    ]"
  >
    <h1>Dynamic Style</h1>
  </div>
</template>

<script setup lang="ts">
import {
      
       ref } from "vue";
const fontSize = ref("18px");
const lineHeight = ref("1.5");
</script>

猜你喜欢

转载自blog.csdn.net/to_the_Future/article/details/130883085