Vue.js 样式绑定
核对 Vue 2 v-bind:class 的对象语法、静态类共存、数据与计算属性对象、数组与三元语法,以及 v-bind:style 内联对象、数组覆盖和自动前缀特性。
学完这一章,你能够
- 核对 Vue 2 v-bind:class 的对象语法、静态类共存、数据与计算属性对象、数组与三元语法,以及 v-bind:style 内联对象、数组覆盖和自动前缀特性。
v-bind:class 对象语法、静态类共存与计算属性对象
`class` 与 `style` 虽同属 HTML 属性,但 Vue.js 对 `v-bind` 处理这两项时做了专门增强:绑定表达式结果除字符串外,还支持对象与数组结构。使用对象语法 `v-bind:class="{ 'active': isActive }"` 可按布尔值动态开关类名——当 `isActive` 为 `true` 时渲染为 `<div class="active"></div>`。本站离线 Chromium 实测 `isActive=true` 时元素挂上 `active` 类并呈现绿色背景 `rgb(0, 128, 0)`,切换为 `false` 后类名清空。
对象中可同时声明多个键以切换多个类名,且 `v-bind:class` 能与普通静态 `class="static"` 共存合并。例如 `class="static" v-bind:class="{ 'active': isActive, 'text-danger': hasError }"` 最终合并为 `static active text-danger`,按样式表层叠顺序 `.text-danger` 的红色背景覆盖 `.active` 的绿色背景;也可直接把整份对象定义在 `data` 的 `classObject` 中传入,渲染结果完全一致。本站实测验证 `c2` 最终类名为 `static active text-danger`、背景色被覆盖为 `rgb(255, 0, 0)`,绑定数据对象的 `c3` 与其类名及背景色完全一致。
在复杂状态组合下,更推荐将 `v-bind:class` 绑定到一个返回对象的计算属性(`computed`),把多条件判断从模板中抽离。本站离线实测 `computedClassObj`:当 `isActive: true` 且 `error: { value: true, type: 'fatal' }` 时,元素类名为 `['base', 'text-danger']`(不激活 `active`);将 `error.value` 改为 `false` 后,元素响应式切换为 `['base', 'active']`。
v-bind:class 数组语法与三元条件切换
除对象外,还可向 `v-bind:class` 传入数组以依次应用多个类名变量(如 `[activeClass, errorClass]` 渲染为 `class="active text-danger"`);需要按条件控制数组中某一项时,可使用三元表达式 `[errorClass, isActive ? activeClass : '']` 使 `errorClass` 始终生效而仅在 `isActive` 为真时追加 `activeClass`。本站离线实测核验 `c5` 渲染为 `active text-danger`,`c6` 在 `isActive=true` 时为 `text-danger active`,置为 `false` 后收缩为 `text-danger`。
v-bind:style 内联样式对象、数组合并与前缀侦测
`v-bind:style` 的对象语法直观对应 CSS 声明(属性名可用驼峰如 `fontSize` 或加引号的短横线形式),例如 `v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"` 渲染为 `color: green; font-size: 30px;`;同样可以直接绑定至 `data` 中的 `styleObject` 让模板更清晰。本站离线 Chromium 实测 `s1` 与 `s2` 计算样式均为 `color: rgb(0, 128, 0)`、`fontSize: 30px`。
`v-bind:style` 也支持数组语法(如 `[baseStyles, overridingStyles]`),按顺序将多个样式对象合并应用到同一元素,靠后的同名属性覆盖前者。此外,在真实 Vue 2 运行时中,当 `v-bind:style` 使用需要浏览器厂商前缀的 CSS 属性(如 `transform`)时,Vue 会自动侦测运行环境并按需补全前缀。本站离线实测数组合并后 `s3` 计算样式由后置对象覆盖为 `color: rgb(220, 38, 38)`、`fontSize: 28px`、`fontWeight: 700`,且 `transform: translateX(10px)` 精确计算为 `matrix(1, 0, 0, 1, 10, 0)`。
离线 Chromium 核验 v-bind:class 对象/计算属性/数组与 v-bind:style 对象/数组样式覆盖
展开查看收起
"""Offline Playwright Chromium lab for Vue 2 Chapter 10 (vue-class-style)."""
import json
from playwright.sync_api import sync_playwright
MINI_VUE2_STYLE_JS = r"""
(function (global) {
class Dep {
constructor() { this.subs = new Set(); }
depend() { if (Dep.target) this.subs.add(Dep.target); }
notify() { Array.from(this.subs).forEach(w => w.update()); }
}
Dep.target = null;
class Watcher {
constructor(vm, getter, cb) {
this.vm = vm;
this.getter = getter;
this.cb = cb;
this.value = this.get();
}
get() {
Dep.target = this;
const v = this.getter.call(this.vm);
Dep.target = null;
return v;
}
update() {
const oldVal = this.value;
const newVal = this.get();
this.value = newVal;
if (this.cb) this.cb.call(this.vm, newVal, oldVal);
}
}
function observe(obj) {
if (!obj || typeof obj !== 'object') return;
Object.keys(obj).forEach(key => {
let val = obj[key];
if (val && typeof val === 'object') observe(val);
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() { dep.depend(); return val; },
set(newVal) {
if (newVal === val) return;
val = newVal;
if (val && typeof val === 'object') observe(val);
dep.notify();
}
});
});
}
function evalExpr(vm, expr) {
return new Function('with(this){ return (' + expr + '); }').call(vm);
}
function resolveClasses(val) {
const out = [];
if (typeof val === 'string') {
val.split(/\s+/).filter(Boolean).forEach(c => out.push(c));
} else if (Array.isArray(val)) {
val.forEach(item => resolveClasses(item).forEach(c => out.push(c)));
} else if (val && typeof val === 'object') {
Object.keys(val).forEach(k => { if (val[k]) out.push(k); });
}
return out;
}
function applyStyleBinding(el, val) {
el.removeAttribute('style');
const objs = Array.isArray(val) ? val : [val];
for (const obj of objs) {
if (!obj || typeof obj !== 'object') continue;
Object.keys(obj).forEach(prop => {
el.style[prop] = obj[prop];
});
}
}
class Vue {
constructor(options) {
this.$data = options.data || {};
observe(this.$data);
Object.keys(this.$data).forEach(k => {
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get: () => this.$data[k],
set: (v) => { this.$data[k] = v; }
});
});
const computed = options.computed || {};
Object.keys(computed).forEach(k => {
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get: () => computed[k].call(this)
});
});
this.$el = document.querySelector(options.el);
if (this.$el) this._compile(this.$el);
}
_compile(root) {
root.querySelectorAll('*').forEach(el => {
const staticClasses = (el.getAttribute('class') || '').split(/\s+/).filter(Boolean);
Array.from(el.attributes).forEach(attr => {
if (attr.name === 'v-bind:class' || attr.name === ':class') {
const exp = attr.value.trim();
el.removeAttribute(attr.name);
const apply = (val) => {
const dyn = resolveClasses(val);
el.className = staticClasses.concat(dyn).join(' ');
};
const w = new Watcher(this, () => evalExpr(this, exp), apply);
apply(w.value);
} else if (attr.name === 'v-bind:style' || attr.name === ':style') {
const exp = attr.value.trim();
el.removeAttribute(attr.name);
const apply = (val) => applyStyleBinding(el, val);
const w = new Watcher(this, () => evalExpr(this, exp), apply);
apply(w.value);
}
});
});
}
}
global.Vue = Vue;
})(window);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue 2 样式绑定 class 与 style 实验</title>
<style>
.static {{ width: 100px; height: 100px; }}
.active {{ width: 100px; height: 100px; background-color: green; }}
.text-danger {{ background-color: red; }}
.base {{ border: 2px solid #222; }}
</style>
</head>
<body>
<div id="app">
<div id="c1" v-bind:class="{{ 'active': isActive }}"></div>
<div id="c2" class="static" v-bind:class="{{ 'active': isActive, 'text-danger': hasError }}"></div>
<div id="c3" class="static" v-bind:class="dataClassObj"></div>
<div id="c4" v-bind:class="computedClassObj"></div>
<div id="c5" v-bind:class="[activeClass, errorClass]"></div>
<div id="c6" v-bind:class="[errorClass, isActive ? activeClass : '']"></div>
<div id="s1" v-bind:style="{{ color: activeColor, fontSize: fontSize + 'px' }}">蓝色天空</div>
<div id="s2" v-bind:style="styleObject">蓝色天空</div>
<div id="s3" v-bind:style="[baseStyles, overridingStyles]">蓝色天空</div>
</div>
<script>{MINI_VUE2_STYLE_JS}</script>
<script>
window.vm = new Vue({{
el: '#app',
data: {{
isActive: true,
hasError: true,
dataClassObj: {{ active: true, 'text-danger': true }},
error: {{ value: true, type: 'fatal' }},
activeClass: 'active',
errorClass: 'text-danger',
activeColor: 'green',
fontSize: 30,
styleObject: {{ color: 'green', fontSize: '30px' }},
baseStyles: {{ color: 'green', fontSize: '30px' }},
overridingStyles: {{ color: '#dc2626', fontSize: '28px', fontWeight: '700', transform: 'translateX(10px)' }}
}},
computed: {{
computedClassObj: function () {{
return {{
base: true,
active: this.isActive && !this.error.value,
'text-danger': this.error.value && this.error.type === 'fatal'
}};
}}
}}
}});
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML_DOC)
# Case 1: Object syntax single, multi + static coexistence, data object binding
res1 = page.evaluate("""() => {
const c1 = document.getElementById('c1');
const c2 = document.getElementById('c2');
const c3 = document.getElementById('c3');
const c1True = { cls: c1.className, bg: getComputedStyle(c1).backgroundColor };
const c2Cls = c2.className;
const c2Bg = getComputedStyle(c2).backgroundColor;
const c3Cls = c3.className;
const c3Bg = getComputedStyle(c3).backgroundColor;
window.vm.isActive = false;
const c1False = c1.className;
window.vm.isActive = true;
return {
c1_true_class: c1True.cls,
c1_true_bg: c1True.bg,
c1_false_class: c1False,
c2_class: c2Cls,
c2_bg_overridden: c2Bg,
c3_matches_c2: (c3Cls === c2Cls && c3Bg === c2Bg)
};
}""")
exp1 = {
"c1_true_class": "active",
"c1_true_bg": "rgb(0, 128, 0)",
"c1_false_class": "",
"c2_class": "static active text-danger",
"c2_bg_overridden": "rgb(255, 0, 0)",
"c3_matches_c2": True,
}
cases.append({
"name": "class_object_single_multi_and_data_obj",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: Computed property returning class object
res2 = page.evaluate(r"""() => {
const c4 = document.getElementById('c4');
const fatalClasses = c4.className.split(/\s+/).filter(Boolean);
window.vm.error.value = false;
const clearedClasses = c4.className.split(/\s+/).filter(Boolean);
return { fatal_classes: fatalClasses, cleared_classes: clearedClasses };
}""")
exp2 = {
"fatal_classes": ["base", "text-danger"],
"cleared_classes": ["base", "active"],
}
cases.append({
"name": "class_computed_object_pattern",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: Array syntax and ternary expression inside class array
res3 = page.evaluate("""() => {
const c5 = document.getElementById('c5');
const c6 = document.getElementById('c6');
const c6Active = c6.className;
window.vm.isActive = false;
const c6Inactive = c6.className;
return {
c5_class: c5.className,
c6_active_class: c6Active,
c6_inactive_class: c6Inactive
};
}""")
exp3 = {
"c5_class": "active text-danger",
"c6_active_class": "text-danger active",
"c6_inactive_class": "text-danger",
}
cases.append({
"name": "class_array_and_ternary_syntax",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
# Case 4: Inline style object, bound data styleObject, array override & transform
res4 = page.evaluate("""() => {
const s1 = getComputedStyle(document.getElementById('s1'));
const s2 = getComputedStyle(document.getElementById('s2'));
const s3 = getComputedStyle(document.getElementById('s3'));
return {
s1_color: s1.color,
s1_font_size: s1.fontSize,
s2_matches_s1: (s2.color === s1.color && s2.fontSize === s1.fontSize),
s3_color: s3.color,
s3_font_size: s3.fontSize,
s3_font_weight: s3.fontWeight,
s3_transform: s3.transform
};
}""")
exp4 = {
"s1_color": "rgb(0, 128, 0)",
"s1_font_size": "30px",
"s2_matches_s1": True,
"s3_color": "rgb(220, 38, 38)",
"s3_font_size": "28px",
"s3_font_weight": "700",
"s3_transform": "matrix(1, 0, 0, 1, 10, 0)",
}
cases.append({
"name": "inline_style_object_data_array_and_transform",
"passed": res4 == exp4,
"expected": exp4,
"actual": res4,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不会覆盖,Vue 会把静态 `class` 与 `:class` 计算出的动态类名合并到同一列表中;在 `:style` 数组中,靠后对象中的同名 CSS 属性会覆盖前面对象的声明。