Vue3 指令
核对 Vue 3 六大常用内置指令(v-bind、v-if、v-show、v-for、v-on、v-model)的定位差异、扩展指令概览及完整离线交互实测。
学完这一章,你能够
- 核对 Vue 3 六大常用内置指令(v-bind、v-if、v-show、v-for、v-on、v-model)的定位差异、扩展指令概览及完整离线交互实测。
Vue 指令的定位与常用指令总览
Vue 指令(Directives)是以 `v-` 为前缀的特殊 HTML 模板属性,用于将响应式数据绑定到 DOM 或对元素施加特定交互行为。相比手写原生 DOM 监听与刷新逻辑,指令能用更简洁的声明式代码构建响应式页面。除下表六大常用指令外,Vue 3 还内置了 `v-text`、`v-html` 等指令,并支持注册自定义指令以满足底层 DOM 操作需求。
核心指令实测:双向绑定、属性绑定与条件/列表渲染
`v-model` 在表单控件与组件状态之间建立双向数据绑定,`v-bind` 则把组件数据映射到 HTML 元素的属性(例如 `v-bind:src`)。本站离线 Chromium 实测验证输入框初始值与绑定段落同步为 `Hello Vue!!`,填入 `Vue3 Directives` 后段落即时同步更新;同时使用离线内联 SVG Data URI 实测 `v-bind:src` 从矩形图标动态切换为圆形图标。
`v-if` 与 `v-else` 按布尔表达式决定是否向 DOM 挂载对应分支,而 `v-for` 结合 `:key` 按数组长度循环渲染节点。本站离线 Chromium 实测验证 `showMessage: true` 时 DOM 仅存在 `Hello Vue!` 节点(`v-else` 节点为 `null`),切换为 `false` 后前者销毁且 DOM 出现 `Goodbye Vue!`;`v-for` 初始渲染 `['1:Item 1', '2:Item 2', '3:Item 3']`,追加第 4 项后自动增渲染 `4:Item 4`。
事件监听与 CSS 显示切换(v-on 与 v-show)
`v-on` 用于在元素上注册事件监听器(如 `v-on:click="lightOn = !lightOn"`),常与 `v-show` 配合实现高频开关切换。与 `v-if` 销毁节点不同,`v-show` 始终保留 DOM 节点,仅通过切换内联样式 `display: none` 控制可见性。本站离线 Chromium 实测灯光开关与文本显隐两个场景:初始 `lightOn: false`、`showMessage: true` 时两元素均存在于 DOM 且计算样式 `display` 分别为 `none` 与 `block`;分别点击开关按钮后,`display` 准确翻转为 `block` 与 `none`,且 DOM 节点始终未被销毁。
Vue 3 常用内置指令速查
| 指令 | 核心作用 | 典型用法与简写 |
| `v-bind` | 将响应式数据动态绑定到 HTML 元素属性或组件 Prop | `v-bind:src="imageSrc"`(简写 `:src`) |
| `v-if` | 按表达式真假条件性创建或销毁 DOM 元素与组件 | `v-if="showMessage"` 配合 `v-else` |
| `v-show` | 保留 DOM 节点,仅通过 CSS `display` 控制显示或隐藏 | `v-show="lightOn"` 适合高频切换 |
| `v-for` | 依据数组或对象循环渲染列表元素或组件 | `v-for="item in items" :key="item.id"` |
| `v-on` | 为元素绑定 DOM 事件监听器并触发方法或内联表达式 | `v-on:click="..."`(简写 `@click`) |
| `v-model` | 在表单控件与响应式数据之间建立双向同步绑定 | `<input v-model="message">` |
离线 Chromium 核对六大核心 Vue 3 指令的 DOM 与计算样式行为
展开查看收起
"""Offline Playwright Chromium lab for Vue 3 Chapter 14 (directives)."""
import json
from playwright.sync_api import sync_playwright
SVG_A = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Crect width='24' height='24' fill='%2342b883'/%3E%3C/svg%3E"
SVG_B = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%2335495e'/%3E%3C/svg%3E"
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Directives Offline Lab</title>
<style>
#light-glow {{ width: 40px; height: 40px; background: #ffe066; }}
</style>
</head>
<body>
<section id="sec-model-bind">
<input id="vm-input" type="text" />
<p id="vm-text"></p>
<img id="bind-img" alt="icon" />
</section>
<section id="sec-if-else">
<div id="if-wrap"></div>
</section>
<section id="sec-for">
<ul id="for-list"></ul>
</section>
<section id="sec-on-show">
<div id="light-glow"></div>
<button id="btn-light">开/关</button>
<button id="btn-show">显示/隐藏</button>
<p id="show-p">Hello Vue!</p>
</section>
<script>
function reactive(obj, onChange) {{
return new Proxy(obj, {{
set(t, k, v) {{ t[k] = v; onChange(); return true; }}
}});
}}
// 1. v-model & v-bind:src
const mbState = reactive({{
message: 'Hello Vue!!',
imageSrc: "{SVG_A}"
}}, renderMB);
function renderMB() {{
const inp = document.getElementById('vm-input');
if (inp.value !== mbState.message) inp.value = mbState.message;
document.getElementById('vm-text').textContent = mbState.message;
document.getElementById('bind-img').setAttribute('src', mbState.imageSrc);
}}
document.getElementById('vm-input').addEventListener('input', e => {{
mbState.message = e.target.value;
}});
renderMB();
window.__mbState = mbState;
window.__svgB = "{SVG_B}";
// 2. v-if / v-else
const ifState = reactive({{ showMessage: true }}, renderIf);
function renderIf() {{
const wrap = document.getElementById('if-wrap');
wrap.innerHTML = ifState.showMessage
? '<p id="msg-true">Hello Vue!</p>'
: '<p id="msg-false">Goodbye Vue!</p>';
}}
renderIf();
window.__ifState = ifState;
// 3. v-for
const forItems = [
{{ id: 1, text: 'Item 1' }},
{{ id: 2, text: 'Item 2' }},
{{ id: 3, text: 'Item 3' }}
];
function renderFor() {{
const ul = document.getElementById('for-list');
ul.innerHTML = '';
for (const item of forItems) {{
const li = document.createElement('li');
li.dataset.key = String(item.id);
li.textContent = item.text;
ul.appendChild(li);
}}
}}
renderFor();
window.__pushForItem = (item) => {{ forItems.push(item); renderFor(); }};
// 4. v-on + v-show
const showState = reactive({{ lightOn: false, showMessage: true }}, renderShow);
function renderShow() {{
document.getElementById('light-glow').style.display = showState.lightOn ? '' : 'none';
document.getElementById('show-p').style.display = showState.showMessage ? '' : 'none';
}}
document.getElementById('btn-light').addEventListener('click', () => {{
showState.lightOn = !showState.lightOn;
}});
document.getElementById('btn-show').addEventListener('click', () => {{
showState.showMessage = !showState.showMessage;
}});
renderShow();
</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: v-model two-way sync & v-bind:src
init_text = page.locator("#vm-text").inner_text()
page.fill("#vm-input", "Vue3 Directives")
c1 = page.evaluate("""() => {
const img = document.getElementById('bind-img');
const srcBefore = img.getAttribute('src').includes('rect');
window.__mbState.imageSrc = window.__svgB;
const srcAfter = img.getAttribute('src').includes('circle');
return {
after_text: document.getElementById('vm-text').textContent,
src_before_rect: srcBefore,
src_after_circle: srcAfter
};
}""")
c1["init_text"] = init_text
exp1 = {
"init_text": "Hello Vue!!",
"after_text": "Vue3 Directives",
"src_before_rect": True,
"src_after_circle": True,
}
cases.append({"name": "vmodel_and_vbind_attr", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: v-if / v-else DOM creation & destruction
c2 = page.evaluate("""() => {
const t1 = {
true_el: document.getElementById('msg-true')?.textContent || null,
false_el: document.getElementById('msg-false')?.textContent || null
};
window.__ifState.showMessage = false;
const t2 = {
true_el: document.getElementById('msg-true')?.textContent || null,
false_el: document.getElementById('msg-false')?.textContent || null
};
return { when_true: t1, when_false: t2 };
}""")
exp2 = {
"when_true": {"true_el": "Hello Vue!", "false_el": None},
"when_false": {"true_el": None, "false_el": "Goodbye Vue!"},
}
cases.append({"name": "vif_velse_conditional_dom", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: v-for keyed list rendering
c3 = page.evaluate("""() => {
const init = Array.from(document.querySelectorAll('#for-list li')).map(li => li.dataset.key + ':' + li.textContent);
window.__pushForItem({ id: 4, text: 'Item 4' });
const after = Array.from(document.querySelectorAll('#for-list li')).map(li => li.dataset.key + ':' + li.textContent);
return { init, after };
}""")
exp3 = {
"init": ["1:Item 1", "2:Item 2", "3:Item 3"],
"after": ["1:Item 1", "2:Item 2", "3:Item 3", "4:Item 4"],
}
cases.append({"name": "vfor_keyed_list", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: v-on click handler + v-show CSS display toggle
before_show = page.evaluate("""() => ({
light_display: getComputedStyle(document.getElementById('light-glow')).display,
msg_display: getComputedStyle(document.getElementById('show-p')).display,
both_in_dom: Boolean(document.getElementById('light-glow') && document.getElementById('show-p'))
})""")
page.click("#btn-light")
page.click("#btn-show")
after_show = page.evaluate("""() => ({
light_display: getComputedStyle(document.getElementById('light-glow')).display,
msg_display: getComputedStyle(document.getElementById('show-p')).display,
both_in_dom: Boolean(document.getElementById('light-glow') && document.getElementById('show-p'))
})""")
c4 = {"before": before_show, "after": after_show}
exp4 = {
"before": {"light_display": "none", "msg_display": "block", "both_in_dom": True},
"after": {"light_display": "block", "msg_display": "none", "both_in_dom": True},
}
cases.append({"name": "von_and_vshow_display_toggle", "passed": c4 == exp4, "expected": exp4, "actual": c4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
v-if 为假时不渲染或直接移除 DOM 节点,适合切换频率较低的条件块;v-show 始终保留 DOM 节点并仅修改 CSS display 属性,适合频繁切换显隐的交互元素。