Skip to content

样式绑定

Vue 专门为 v-bind 的用法绑定 class 和 style 提供了特殊的功能增强,表达式的值支持字符串、对象和数组。

class 类样式绑定

:classv-bind:class 的缩写)

绑定对象

vue
<template>
    <div class="div-box">
        <!-- 内联字面量 -->
        <div :class="{ active: isActive }">Class Bind Obj Active</div>
        <!-- 内联对象 -->
        <div class="static" :class="classObj">Class Bind Obj Not Active</div>
    </div>
</template>

<script setup lang="ts">

const isActive = true;

const classObj = {
    active: !isActive,
    "text-danger": isActive
}

</script>

<style scoped>
.active {
    color: red;
}

.static {
    font-size: 20px;
    font-weight: bold;
}

.text-danger {
    background-color: yellow;
}
</style>

绑定数组

vue
<template>
    <div class="div-box">
        <!-- 使用数组渲染多个 class -->
        <div :class="['class1', 'class2']">Class Bind Array</div>

        <!-- 使用三元表达式 -->
        <div :class="[isActive ? 'class1' : 'class2', 'errorClass']">Ternary Expression</div>

        <!-- 在数组中使用对象语法 -->
        <div :class="[{ [activeClass]: isActive }, 'errorClass']">Object Syntax</div>
    </div>
</template>

<script setup lang="ts">
const activeClass = "class1";
const isActive = true;
</script>

<style scoped>
.class1 {
    font-size: 20px;
    font-weight: bold;
}

.class2 {
    color: red;
}

.errorClass {
    background-color: yellow;
}
</style>

style 内联样式绑定

:stylev-bind:style 的缩写)

绑定对象

vue
<template>
    <div class="div-box">
        <!-- 内联字面量: camelCase (推荐)-->
        <div :style="{ color: 'red', fontSize: '20px' }">Style Bind Obj Literal</div>

        <!-- 内联字面量:kebab-case -->
        <div :style="{ 'background-color': 'yellow', 'font-size': '20px' }">Style Bind Obj Literal</div>

        <!-- 内联对象 -->
        <div :style="styleObj">Style Bind Obj</div>
    </div>
</template>

<script setup lang="ts">
const styleObj = {
    color: "red",
    fontSize: "20px"
}
</script>

绑定数组

vue
<template>
    <div class="div-box">
        <!-- 内联数组 -->
        <div :style="[styleObj1, styleObj2]">Style Bind Arr</div>
    </div>
</template>

<script setup lang="ts">
const styleObj1 = {
    color: "red",
    fontSize: "20px"
}

const styleObj2 = {
    backgroundColor: "yellow",
    fontSize: "20px"
}
</script>