Vue3 声明式渲染
核对 Vue 3 声明式渲染的数据驱动思想(MVVM 关系)、插值表达式、属性绑定、条件/列表渲染、表单双向绑定、事件处理与计算属性实测。
学完这一章,你能够
- 核对 Vue 3 声明式渲染的数据驱动思想(MVVM 关系)、插值表达式、属性绑定、条件/列表渲染、表单双向绑定、事件处理与计算属性实测。
声明式渲染的数据驱动思想
声明式渲染(Declarative Rendering)的核心是以数据驱动视图,而非手写命令式 DOM 查找与节点拼接代码。Vue 3 采用类似 HTML 的模板语法,让开发者只需声明“界面应当如何随状态呈现”,再结合响应式数据与指令(`v-if`、`v-for`、`v-bind` 等),由 ViewModel 层在数据变动时自动完成 DOM 更新,使代码聚焦于业务逻辑。
数据绑定:插值表达式与属性绑定
数据绑定是声明式渲染的基石。文本插值使用双花括号 `{{ }}` 把组件数据写入模板,且括号内不仅限于简单属性名,还支持合法的单条 JavaScript 表达式(例如 `message.split('').reverse().join('')`)。
当需要动态绑定 HTML 标签属性(如 `href`、`class`、`src`)时,应使用 `v-bind` 指令(例如 `v-bind:href="url"`)。本站离线 Chromium 实测验证初始渲染 `<h1>` 为 `Hello, Vue 3!`、反转表达式为 `!3 euV ,olleH`、链接 `href` 为 `https://example.org/vue3`;随后将 `message` 改为 `Vue3!`、`url` 改为 `https://vuejs.org/`,三个 DOM 节点均自动同步更新。
条件渲染与列表渲染
条件渲染通过 `v-if`、`v-else-if`、`v-else` 按布尔条件决定节点是否出现在 DOM 中。本站离线 Chromium 实测点击切换按钮反转 `isVisible`,`<p>` 节点在 `这段文本是可见的` -> `null`(DOM 移除)-> 恢复渲染之间准确切换。
列表渲染通过 `v-for` 遍历数组生成对应元素,并为每项指定唯一 `:key` 帮助框架追踪节点复用与最小化更新。本站离线 Chromium 实测初始渲染 `['1:Vue 3', '2:JavaScript', '3:HTML']` 三项,向数组追加 `{ id: 4, name: 'CSS' }` 后列表自动增至四项并保留各自 `key`。
双向数据绑定、事件处理与计算属性
表单输入使用 `v-model` 建立控件值与组件状态的双向同步,用户输入时即时写回数据并刷新绑定视图;用户交互通过 `v-on`(如 `v-on:click="increment"`)声明式绑定事件处理方法。本站离线 Chromium 实测向 `v-model` 输入框键入 `声明式渲染` 后段落立即同步为 `你输入了:声明式渲染`,连续点击 `v-on:click` 按钮三次后计数器更新为 `点击次数:3`。
衍生数值应通过计算属性 `computed` 声明式表达,仅在依赖状态改变时重新求值。本站离线 Chromium 实测以 `amount: 100` 计算 10% 税后金额 `computedAmount` 得 `110`,将 `amount` 更新为 `250` 后视图自动刷新为 `原始金额:250` 与 `税后金额:275`。
离线 Chromium 核对 Vue 3 声明式渲染六大场景联动
"""Offline Playwright Chromium lab for Vue 3 Chapter 13 (declarative-rendering)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 Declarative Rendering Offline Lab</title></head>
<body>
<section id="sec-bind">
<h1 id="msg-h1"></h1>
<h2 id="msg-rev"></h2>
<a id="site-link">点我</a>
</section>
<section id="sec-cond-list">
<div id="vis-wrap"></div>
<button id="btn-toggle">切换可见性</button>
<ul id="item-list"></ul>
</section>
<section id="sec-model-event">
<input id="msg-in" placeholder="输入一些文本" />
<p id="msg-out"></p>
<button id="btn-inc">点击我</button>
<p id="cnt-out"></p>
</section>
<section id="sec-computed">
<p id="raw-amount"></p>
<p id="tax-amount"></p>
</section>
<script>
function reactive(obj, notify) {
return new Proxy(obj, {
set(target, prop, value) {
target[prop] = value;
notify();
return true;
}
});
}
// 1. Interpolation & v-bind
const bindState = reactive({
message: 'Hello, Vue 3!',
url: 'https://example.org/vue3'
}, renderBind);
function renderBind() {
document.getElementById('msg-h1').textContent = bindState.message;
document.getElementById('msg-rev').textContent = bindState.message.split('').reverse().join('');
document.getElementById('site-link').setAttribute('href', bindState.url);
}
renderBind();
window.__bindState = bindState;
// 2. Conditional rendering (v-if) & list rendering (v-for)
const itemsArr = [
{ id: 1, name: 'Vue 3' },
{ id: 2, name: 'JavaScript' },
{ id: 3, name: 'HTML' }
];
const clState = reactive({ isVisible: true, version: 0 }, renderCondList);
function renderCondList() {
const wrap = document.getElementById('vis-wrap');
wrap.innerHTML = clState.isVisible ? '<p id="vis-msg">这段文本是可见的</p>' : '';
const ul = document.getElementById('item-list');
ul.innerHTML = '';
for (const item of itemsArr) {
const li = document.createElement('li');
li.dataset.key = String(item.id);
li.textContent = item.name;
ul.appendChild(li);
}
}
document.getElementById('btn-toggle').addEventListener('click', () => {
clState.isVisible = !clState.isVisible;
});
renderCondList();
window.__addItem = (item) => { itemsArr.push(item); clState.version++; };
// 3. v-model & v-on
const meState = reactive({ message: '', count: 0 }, renderModelEvent);
function renderModelEvent() {
const inp = document.getElementById('msg-in');
if (inp.value !== meState.message) inp.value = meState.message;
document.getElementById('msg-out').textContent = '你输入了:' + meState.message;
document.getElementById('cnt-out').textContent = '点击次数:' + meState.count;
}
document.getElementById('msg-in').addEventListener('input', (e) => {
meState.message = e.target.value;
});
document.getElementById('btn-inc').addEventListener('click', () => {
meState.count += 1;
});
renderModelEvent();
// 4. Computed amount with 10% tax
const compState = reactive({ amount: 100 }, renderComputed);
function computedAmount() {
return Number((compState.amount * 1.1).toFixed(2));
}
function renderComputed() {
document.getElementById('raw-amount').textContent = '原始金额:' + compState.amount;
document.getElementById('tax-amount').textContent = '税后金额:' + computedAmount();
}
renderComputed();
window.__compState = compState;
</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(viewport={"width": 900, "height": 600})
page.set_content(HTML_DOC)
# Case 1: Interpolation, JS expression & v-bind:href
c1 = page.evaluate("""() => {
const init = {
h1: document.getElementById('msg-h1').textContent,
rev: document.getElementById('msg-rev').textContent,
href: document.getElementById('site-link').getAttribute('href')
};
window.__bindState.message = 'Vue3!';
window.__bindState.url = 'https://vuejs.org/';
const updated = {
h1: document.getElementById('msg-h1').textContent,
rev: document.getElementById('msg-rev').textContent,
href: document.getElementById('site-link').getAttribute('href')
};
return { init, updated };
}""")
exp1 = {
"init": {"h1": "Hello, Vue 3!", "rev": "!3 euV ,olleH", "href": "https://example.org/vue3"},
"updated": {"h1": "Vue3!", "rev": "!3euV", "href": "https://vuejs.org/"},
}
cases.append({"name": "interpolation_and_vbind", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: v-if toggling & v-for keyed list reactivity
vis_init = page.evaluate("() => document.getElementById('vis-msg')?.textContent || null")
page.click("#btn-toggle")
vis_hidden = page.evaluate("() => document.getElementById('vis-msg')?.textContent || null")
page.click("#btn-toggle")
vis_restored = page.evaluate("() => document.getElementById('vis-msg')?.textContent || null")
list_init = page.evaluate("() => Array.from(document.querySelectorAll('#item-list li')).map(el => el.dataset.key + ':' + el.textContent)")
page.evaluate("() => window.__addItem({ id: 4, name: 'CSS' })")
list_after = page.evaluate("() => Array.from(document.querySelectorAll('#item-list li')).map(el => el.dataset.key + ':' + el.textContent)")
c2 = {
"vis_init": vis_init,
"vis_hidden": vis_hidden,
"vis_restored": vis_restored,
"list_init": list_init,
"list_after": list_after,
}
exp2 = {
"vis_init": "这段文本是可见的",
"vis_hidden": None,
"vis_restored": "这段文本是可见的",
"list_init": ["1:Vue 3", "2:JavaScript", "3:HTML"],
"list_after": ["1:Vue 3", "2:JavaScript", "3:HTML", "4:CSS"],
}
cases.append({"name": "conditional_and_list_rendering", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: v-model two-way binding & v-on:click counter
page.fill("#msg-in", "声明式渲染")
page.click("#btn-inc")
page.click("#btn-inc")
page.click("#btn-inc")
c3 = page.evaluate("""() => ({
input_val: document.getElementById('msg-in').value,
msg_out: document.getElementById('msg-out').textContent,
cnt_out: document.getElementById('cnt-out').textContent
})""")
exp3 = {
"input_val": "声明式渲染",
"msg_out": "你输入了:声明式渲染",
"cnt_out": "点击次数:3",
}
cases.append({"name": "vmodel_and_von_events", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: Computed tax calculation
c4 = page.evaluate("""() => {
const before = {
raw: document.getElementById('raw-amount').textContent,
tax: document.getElementById('tax-amount').textContent
};
window.__compState.amount = 250;
const after = {
raw: document.getElementById('raw-amount').textContent,
tax: document.getElementById('tax-amount').textContent
};
return { before, after };
}""")
exp4 = {
"before": {"raw": "原始金额:100", "tax": "税后金额:110"},
"after": {"raw": "原始金额:250", "tax": "税后金额:275"},
}
cases.append({"name": "computed_tax_amount", "passed": c4 == exp4, "expected": exp4, "actual": c4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对插值反转与 v-bind:href 动态切换,v-if 移除/恢复与 v-for 增项,v-model 同步与 v-on 三次点击计数,以及 computed 税后金额 110→275 自动重算。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:fd6c9d8df2f97a70302131b0ec3733b25c6b771f97b51d9b2c306db7fe065bb1
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:df3b1fb9f9f83aa9359227d4bb260b1c0954f201e1f52ca3b82285907fdb4c09
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
声明式渲染与传统手动 DOM 操作相比,在状态更新链路上的核心差异是什么?
展开参考解答
手动 DOM 操作需要开发者在每次数据变更后显式查找节点并逐一修改属性或文本;声明式渲染只需在模板中声明视图与数据的绑定关系,状态变化时由响应式系统自动计算并应用最小 DOM 更新。