Vue3 样式绑定
系统梳理 Vue 3 中 :class 与 :style 的对象、计算属性、数组、多重值回退及单根/多根组件 $attrs.class 透传规则,并附离线 Chromium 实测。
学完这一章,你能够
- 系统梳理 Vue 3 中 :class 与 :style 的对象、计算属性、数组、多重值回退及单根/多根组件 $attrs.class 透传规则,并附离线 Chromium 实测。
Class 对象语法与计算属性绑定
HTML 元素的 `class` 与 `style` 属于常用样式属性,Vue 3 允许使用 `v-bind`(简写为 `:class` 与 `:style`)进行动态绑定。与普通属性仅拼接字符串不同,Vue 对 `class` 和 `style` 做了专门增强,表达式除了字符串外,还原生支持对象与数组结构。
对象语法 `:class="{ active: isActive }"` 根据字段真假动态添加或移除对应类名:当 `isActive` 为 `true` 时渲染为 `<div class="active"></div>`,为 `false` 时移除该类。
`:class` 可在同一对象内同时控制多个类名,并与静态 `class="static"` 共存合并而非覆盖。本站离线 Chromium 实测:初始 `isActive=false, hasError=true` 时元素渲染为 `static text-danger` 且计算背景色为 `rgb(255, 0, 0)`;将 `isActive` 改为 `true` 后,类名自动合并为 `static active text-danger`。
当类名判断较复杂时,可直接绑定 `data` 中的 `classObject` 对象,或绑定一个返回对象的计算属性(如 `active: isActive && !error`、`'text-danger': error && error.type === 'fatal'`)。实测 `error=null` 且 `isActive=true` 时计算结果为 `static active`,切换为 `{ type: 'fatal' }` 后自动变为 `static text-danger`。
Class 数组语法与条件切换
数组语法 `:class="[activeClass, errorClass]"` 可将多个响应式字符串类名依次合并应用到元素上。实测绑定静态类 `static` 与数组 `['active', 'text-danger']` 后,真实 DOM `className` 精确渲染为 `static active text-danger`。
在数组中配合三元表达式 `[isActive ? activeClass : '', errorClass]`(或在数组项内嵌套对象语法)可实现按条件保留常驻类并按需附加激活类。实测 `isActive=false` 时渲染为 `static text-danger`,切换为 `true` 后即时变为 `static active text-danger`。
Style 内联样式、数组合并与多重值
`:style` 支持内联对象语法,CSS 属性名可使用驼峰(`fontSize`)或短横线引号形式(`'font-size'`),也可以直接绑定整个 `styleObject` 使模板更简洁。实测绑定 `{ color: 'red', fontSize: 30 + 'px' }` 后,Chromium `getComputedStyle` 测得 `color` 为 `rgb(255, 0, 0)`、`fontSize` 为 `30px`。
`:style` 传入数组 `[baseStyles, overridingStyles]` 时会按顺序合并多个样式对象,后者覆盖前者同名属性;需要厂商前缀的属性(如 `transform`)Vue 会自动补全。同时支持多重值数组(如 `{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }`),浏览器仅应用数组中最后一个受支持的值——实测 Chromium 中 `[baseStyles, overridingStyles]` 合并为 `rgb(0, 0, 255)` / `32px` / `700`,多重值 `display` 精确解析为 `flex`。
自定义组件上的 Class 透传与多根节点
在单根元素的自定义组件上使用静态 `class` 或动态 `:class` 时,外部传入的类名会自动透传并追加到组件根元素上,不会覆盖根元素原有类名。实测根模板含 `classA classB`、调用方传入 `classC classD` 时,最终合并为 `classA classB classC classD`。
当组件拥有多个根节点(Fragment)时,Vue 无法自动决定由哪个节点接收外部类,必须通过 `:class="$attrs.class"` 显式指定目标节点;编写多行模板字符串时注意使用反引号 `` ` `` 而非单引号 `'`。实测绑定 `$attrs.class` 到 `<p>` 后,`<p>` 获得 `classA`,同级 `<span>` 保持空类名。
在离线 Chromium 中验证对象/数组/计算属性 class 绑定、style 多重值与组件 $attrs.class
展开查看收起
"""Offline Playwright Chromium lab for Vue 3 Ch 21: class and style binding."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Class & Style Binding Lab</title>
<style>
.static { padding: 4px; }
.active { background-color: rgb(0, 128, 0); }
.text-danger { background-color: rgb(255, 0, 0); color: rgb(255, 255, 255); }
.classA { border-width: 1px; }
.classB { border-style: solid; }
.classC { margin-top: 2px; }
.classD { margin-bottom: 2px; }
</style>
</head>
<body>
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
<div id="c4"></div>
<div id="s1">Vue3 样式绑定</div>
<div id="s2">样式数组合并</div>
<div id="s3">多重值回退</div>
<div id="comp-single"></div>
<div id="comp-multi"></div>
<script>
// Minimal ES Proxy reactivity + Vue 3 class/style binding semantics (offline)
function normalizeClass(value) {
let res = [];
if (typeof value === 'string') {
res.push(value);
} else if (Array.isArray(value)) {
for (const item of value) {
const normalized = normalizeClass(item);
if (normalized) res.push(normalized);
}
} else if (value && typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key]) res.push(key);
}
}
return res.join(' ').trim().replace(/\s+/g, ' ');
}
function applyClass(el, staticClass, dynamicBinding) {
const parts = [];
if (staticClass) parts.push(staticClass);
const dyn = normalizeClass(dynamicBinding);
if (dyn) parts.push(dyn);
el.className = parts.join(' ').trim();
}
function applyStyle(el, styleBinding) {
el.removeAttribute('style');
const objects = Array.isArray(styleBinding) ? styleBinding : [styleBinding];
for (const obj of objects) {
if (!obj) continue;
for (const [prop, val] of Object.entries(obj)) {
const cssProp = prop.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
if (Array.isArray(val)) {
for (const candidate of val) {
el.style.setProperty(cssProp, candidate);
}
} else if (val != null) {
el.style.setProperty(cssProp, String(val));
}
}
}
}
function reactive(target, onChange) {
return new Proxy(target, {
set(obj, prop, val) {
obj[prop] = val;
onChange();
return true;
}
});
}
window.runAllTests = function () {
// Case 1: Object syntax + static coexistence + computed classObject
const el1 = document.getElementById('c1');
const el2 = document.getElementById('c2');
const state1 = reactive({ isActive: false, hasError: true, error: null }, render1);
function computedClassObject() {
return {
active: state1.isActive && !state1.error,
'text-danger': !!(state1.error && state1.error.type === 'fatal')
};
}
function render1() {
applyClass(el1, 'static', { active: state1.isActive, 'text-danger': state1.hasError });
applyClass(el2, 'static', computedClassObject());
}
render1();
const initialClass = el1.className;
const initialBg = getComputedStyle(el1).backgroundColor;
state1.isActive = true;
const bothClass = el1.className;
const computedOk = el2.className;
state1.error = { type: 'fatal' };
const computedFatal = el2.className;
// Case 2: Array syntax + ternary
const el3 = document.getElementById('c3');
const el4 = document.getElementById('c4');
const arrState = reactive({ isActive: false, activeClass: 'active', errorClass: 'text-danger' }, render2);
function render2() {
applyClass(el3, 'static', [arrState.activeClass, arrState.errorClass]);
applyClass(el4, 'static', [arrState.isActive ? arrState.activeClass : '', arrState.errorClass]);
}
render2();
const arrStatic = el3.className;
const ternaryFalse = el4.className;
arrState.isActive = true;
const ternaryTrue = el4.className;
// Case 3: Inline style object, array merge, and multi-value array
const s1 = document.getElementById('s1');
const s2 = document.getElementById('s2');
const s3 = document.getElementById('s3');
applyStyle(s1, { color: 'red', fontSize: 30 + 'px' });
const baseStyles = { color: 'green', fontSize: '20px', fontWeight: 'bold' };
const overridingStyles = { color: 'blue', fontSize: '32px' };
applyStyle(s2, [baseStyles, overridingStyles]);
applyStyle(s3, { display: ['-webkit-box', '-ms-flexbox', 'flex'] });
// Case 4: Component class fallthrough (single root vs multi-root $attrs.class)
const singleHost = document.getElementById('comp-single');
const h1 = document.createElement('h1');
h1.textContent = 'Single Root';
applyClass(h1, 'classA classB', 'classC classD');
singleHost.appendChild(h1);
const multiHost = document.getElementById('comp-multi');
const attrs = { class: 'classA' };
const p = document.createElement('p');
p.textContent = 'Forwarded Root';
applyClass(p, '', attrs.class);
const span = document.createElement('span');
span.textContent = 'Sibling Root';
multiHost.append(p, span);
return {
case1: {
initial_class: initialClass,
initial_bg: initialBg,
after_active_true: bothClass,
computed_active: computedOk,
computed_fatal: computedFatal
},
case2: {
array_class: arrStatic,
ternary_false: ternaryFalse,
ternary_true: ternaryTrue
},
case3: {
inline_color: getComputedStyle(s1).color,
inline_font_size: getComputedStyle(s1).fontSize,
merged_color: getComputedStyle(s2).color,
merged_font_size: getComputedStyle(s2).fontSize,
merged_font_weight: getComputedStyle(s2).fontWeight,
multi_display: getComputedStyle(s3).display
},
case4: {
single_root_class: h1.className,
multi_root_p_class: p.className,
multi_root_span_class: span.className
}
};
};
</script>
</body>
</html>
"""
def main():
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML)
out = page.evaluate("window.runAllTests()")
browser.close()
expected = {
"class_object_and_computed_binding": {
"initial_class": "static text-danger",
"initial_bg": "rgb(255, 0, 0)",
"after_active_true": "static active text-danger",
"computed_active": "static active",
"computed_fatal": "static text-danger",
},
"class_array_and_ternary_syntax": {
"array_class": "static active text-danger",
"ternary_false": "static text-danger",
"ternary_true": "static active text-danger",
},
"style_object_array_and_multi_value": {
"inline_color": "rgb(255, 0, 0)",
"inline_font_size": "30px",
"merged_color": "rgb(0, 0, 255)",
"merged_font_size": "32px",
"merged_font_weight": "700",
"multi_display": "flex",
},
"component_single_and_multi_root_attrs": {
"single_root_class": "classA classB classC classD",
"multi_root_p_class": "classA",
"multi_root_span_class": "",
},
}
mapping = [
("class_object_and_computed_binding", out["case1"]),
("class_array_and_ternary_syntax", out["case2"]),
("style_object_array_and_multi_value", out["case3"]),
("component_single_and_multi_root_attrs", out["case4"]),
]
cases = []
for name, actual in mapping:
exp = expected[name]
cases.append({
"name": name,
"expected": exp,
"actual": actual,
"passed": actual == exp,
})
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
多根组件没有唯一根 DOM 元素,Vue 无法推断该把外部 class 合并到哪一个节点,需在目标子元素上通过 :class="$attrs.class" 手动绑定透传属性。