Vue 词条目录
前端Wiki/Vue/基础/应用与模板语法

class 与 style 绑定

绑定 class 与 style 是高频操作。class 三种写法:字符串、对象(键名=类名,值为真则生效)、数组(同时应用多个类)。对象写法最适合状态切换::class="{ active: isActive }" 与静态 class 可共存。

style 绑定同样支持对象与数组,键名用驼峰(fontSize)或短横线(font-size 都行);CSS 变量也能绑::style="{ fontSize: size }"。

  • class 对象写法:{ 类名: 布尔 },最常配合状态开关
  • class 数组写法:[类A, 类B, 条件 ? 类C : '']
  • style 对象写法:{ color: color, fontSize: size + 'px' }
HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>class 与 style 绑定</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<style>
  .active { color: #42b883; font-weight: bold; }
  .danger { background: #ffe4e1; }
</style>
</head>
<body>
  <div id="app">
    <!-- 对象写法:active 类随 isActive 开关 -->
    <p :class="{ active: isActive }" class="base">状态文字</p>
    <!-- 数组写法:按条件上多个类 -->
    <p :class="[isActive ? 'active' : '', { danger: isError }]">组合类</p>
    <!-- style 对象写法 -->
    <p :style="{ color: color, fontSize: size + 'px' }">内联样式</p>
    <button @click="isActive = !isActive">切换</button>
  </div>

<script>
  const { createApp } = Vue;
  createApp({
    data() {
      return { isActive: true, isError: false, color: '#42b883', size: 20 };
    }
  }).mount('#app');
</script>
</body>
</html>
本节要点class/style 绑定用对象/数组写法实现动态样式;静态 class 与 :class 自动合并。
🔗 相关词条CSSJavaScriptCSS 特效