Vue3 循环语句
核对 Vue 3 v-for 遍历数组、索引、template 分组、嵌套循环、对象属性、整数范围、计算属性过滤、与 v-if 配合及组件列表 Todo 实战。
学完这一章,你能够
- 核对 Vue 3 v-for 遍历数组、索引、template 分组、嵌套循环、对象属性、整数范围、计算属性过滤、与 v-if 配合及组件列表 Todo 实战。
v-for 遍历数组、索引、template 与嵌套循环
Vue 3 通过 `v-for` 指令基于数组或对象循环渲染对应数量的 DOM 元素,基本语法分为遍历数组 `v-for="(item, index) in items"` 与遍历对象 `v-for="(value, key, index) in object"`。使用 `v-for` 时应为每一项提供唯一 `:key` 属性以便精准追踪和高效复用地更新节点,并支持多层嵌套 `v-for` 渲染二维数组或嵌套数据结构。
遍历数组时既可以仅取当前元素 `site in sites`,也可传入可选第二参数取得从 `0` 开始的索引 `(site, index) in sites`。若每轮迭代需渲染多个并列兄弟节点(如数据项加分隔行),可把 `v-for` 放在 `<template>` 标签上而不产生多余外层元素。本站离线 Chromium 实测验证基础数组渲染 `['1:Alpha', '2:Beta', '3:Gamma']`、带索引渲染 `['0 - Alpha', '1 - Beta', '2 - Gamma']`、`<template v-for>` 展开为 6 个平级 `<li>` 且无 `<template>` 残留,以及二维矩阵嵌套渲染 `[['A1', 'A2'], ['B1', 'B2']]`。
迭代对象、迭代整数与计算属性过滤
`v-for` 同样支持遍历普通 JavaScript 对象的自有可枚举属性:单参数形式获取属性值 `value`,双参数 `(value, key)` 同时获取键名,三参数 `(value, key, index)` 进一步提供属性序号。本站离线 Chromium 实测遍历三字段对象,三种形式分别精确输出值列表、键值拼接列表与带 `0/1/2` 序号的键值列表。
`v-for` 还可接受正整数(如 `v-for="n in 10"`),按 `1` 到 `10`(注意从 `1` 开始而非 `0`)重复渲染模板。当需要对源数组过滤或排序后再展示时,推荐使用计算属性返回派生数组(例如 `evenNumbers` 只保留偶数)而不修改原数组。本站离线 Chromium 实测验证整数循环产出 10 项(首项 `1`、末项 `10`),`evenNumbers` 初始输出 `['2', '4', '6']`,向源数组追加 `8` 后视图自动更新为 `['2', '4', '6', '8']`。
v-for 与 v-if 配合及在自定义组件上使用 v-for
在 Vue 3 中若同一元素上同时书写 `v-if` 与 `v-for`,`v-if` 优先级更高导致无法访问循环变量,因此应将 `v-for` 放在外层 `<template>` 上、再在内层元素使用 `v-if`(例如在 `<select>` 内部按 `index == 1` 区分默认 `<option>` 并配合 `v-model` 同步选中值)。本站离线 Chromium 实测验证下拉框默认选中 `Beta` 并显示 `您选中了:Beta`,切换选项至 `Gamma` 后同步更新为 `您选中了:Gamma`。
自定义组件上同样可以直接使用 `v-for`(需显式提供 `:key`)。由于每个组件拥有独立作用域,循环项不会自动注入子组件,必须通过 Props(如 `:title="todo.title"`)显式传入,避免组件与特定 `v-for` 强耦合,从而保持复用性;删除操作则由子组件触发 `@remove` 事件交回父组件修改数组。本站离线 Chromium 实测 Todo 列表:初始 2 项任务,提交表单新增 `学习组件循环` 后列表增至 3 项且输入框自动清空,点击首项移除按钮后剩余 `['2:编写列表组件', '3:学习组件循环']`。
离线 Chromium 核对 v-for 数组/对象/整数、计算属性过滤、select 联动与 Todo 组件列表
"""Offline Playwright Chromium lab for Vue 3 Chapter 17 (v-for)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 v-for Offline Lab</title></head>
<body>
<ol id="arr-ol"></ol>
<ol id="arr-idx-ol"></ol>
<ul id="tpl-ul"></ul>
<div id="nested-box"></div>
<ul id="obj-val-ul"></ul>
<ul id="obj-kv-ul"></ul>
<ul id="obj-kvi-ul"></ul>
<ul id="int-ul"></ul>
<ul id="even-ul"></ul>
<div id="sel-app">
<select id="site-select"></select>
<div id="sel-out"></div>
</div>
<div id="todo-app">
<form id="todo-form">
<input id="new-todo" placeholder="Add a todo" />
<button id="btn-add-todo" type="submit">Add</button>
</form>
<ul id="todo-ul"></ul>
</div>
<script>
function reactive(obj, onChange) {
return new Proxy(obj, {
set(t, k, v) { t[k] = v; onChange(); return true; }
});
}
// 1. Array v-for, index, <template v-for>, nested v-for
const sites = [{ id: 1, text: 'Alpha' }, { id: 2, text: 'Beta' }, { id: 3, text: 'Gamma' }];
const matrix = [['A1', 'A2'], ['B1', 'B2']];
function renderArr() {
const ol1 = document.getElementById('arr-ol');
const ol2 = document.getElementById('arr-idx-ol');
const tplUl = document.getElementById('tpl-ul');
ol1.innerHTML = ''; ol2.innerHTML = ''; tplUl.innerHTML = '';
sites.forEach((site, idx) => {
const li1 = document.createElement('li'); li1.dataset.key = String(site.id); li1.textContent = site.text; ol1.appendChild(li1);
const li2 = document.createElement('li'); li2.textContent = `${idx} - ${site.text}`; ol2.appendChild(li2);
const liA = document.createElement('li'); liA.textContent = site.text; tplUl.appendChild(liA);
const liB = document.createElement('li'); liB.textContent = '---'; tplUl.appendChild(liB);
});
const nb = document.getElementById('nested-box');
nb.innerHTML = '';
matrix.forEach((row, r) => {
const div = document.createElement('div');
div.dataset.row = String(r);
row.forEach(cell => {
const sp = document.createElement('span'); sp.textContent = cell; div.appendChild(sp);
});
nb.appendChild(div);
});
}
renderArr();
// 2. Object v-for: (value), (value, key), (value, key, index)
const objData = {
name: '蓝色天空',
url: 'https://example.org',
slogan: '掌握前端核心'
};
Object.entries(objData).forEach(([k, v], i) => {
const a = document.createElement('li'); a.textContent = v; document.getElementById('obj-val-ul').appendChild(a);
const b = document.createElement('li'); b.textContent = `${k} : ${v}`; document.getElementById('obj-kv-ul').appendChild(b);
const c = document.createElement('li'); c.textContent = `${i}. ${k} : ${v}`; document.getElementById('obj-kvi-ul').appendChild(c);
});
// 3. Integer range (1..10) & computed filtered evenNumbers
for (let n = 1; n <= 10; n++) {
const li = document.createElement('li'); li.textContent = String(n);
document.getElementById('int-ul').appendChild(li);
}
const numbers = [1, 2, 3, 4, 5, 6];
function renderEvens() {
const ul = document.getElementById('even-ul');
ul.innerHTML = '';
numbers.filter(n => n % 2 === 0).forEach(n => {
const li = document.createElement('li'); li.textContent = String(n); ul.appendChild(li);
});
}
renderEvens();
window.__pushNum = (n) => { numbers.push(n); renderEvens(); };
// 4. <template v-for> + v-if inside <select>
const selSites = [
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' },
{ id: 3, name: 'Gamma' }
];
const selState = reactive({ selOption: 'Beta' }, renderSel);
function renderSel() {
const sel = document.getElementById('site-select');
if (sel.options.length === 0) {
selSites.forEach((site, index) => {
const opt = document.createElement('option');
opt.value = site.name;
opt.textContent = site.name;
if (index === 1) opt.selected = true;
sel.appendChild(opt);
});
}
sel.value = selState.selOption;
document.getElementById('sel-out').textContent = '您选中了:' + selState.selOption;
}
document.getElementById('site-select').addEventListener('change', e => {
selState.selOption = e.target.value;
});
renderSel();
// 5. Component v-for Todo list with props (:title) and @remove event
let nextTodoId = 3;
const todos = [
{ id: 1, title: '阅读 Vue3 文档' },
{ id: 2, title: '编写列表组件' }
];
function renderTodoItem(todo, onRemove) {
const li = document.createElement('li');
li.dataset.key = String(todo.id);
const span = document.createElement('span');
span.className = 'todo-title';
span.textContent = todo.title;
const btn = document.createElement('button');
btn.className = 'btn-rm';
btn.textContent = 'Remove';
btn.addEventListener('click', onRemove);
li.appendChild(span);
li.appendChild(btn);
return li;
}
function renderTodos() {
const ul = document.getElementById('todo-ul');
ul.innerHTML = '';
todos.forEach((todo, idx) => {
ul.appendChild(renderTodoItem(todo, () => {
todos.splice(idx, 1);
renderTodos();
}));
});
}
document.getElementById('todo-form').addEventListener('submit', e => {
e.preventDefault();
const inp = document.getElementById('new-todo');
const txt = inp.value.trim();
if (txt) {
todos.push({ id: nextTodoId++, title: txt });
inp.value = '';
renderTodos();
}
});
renderTodos();
</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: Array, index, <template v-for>, nested v-for
c1 = page.evaluate("""() => ({
basic: Array.from(document.querySelectorAll('#arr-ol li')).map(el => el.dataset.key + ':' + el.textContent),
indexed: Array.from(document.querySelectorAll('#arr-idx-ol li')).map(el => el.textContent),
tpl_items: Array.from(document.querySelectorAll('#tpl-ul li')).map(el => el.textContent),
tpl_has_template_tag: document.querySelector('#tpl-ul template') !== null,
nested: Array.from(document.querySelectorAll('#nested-box > div')).map(d =>
Array.from(d.querySelectorAll('span')).map(s => s.textContent)
)
})""")
exp1 = {
"basic": ["1:Alpha", "2:Beta", "3:Gamma"],
"indexed": ["0 - Alpha", "1 - Beta", "2 - Gamma"],
"tpl_items": ["Alpha", "---", "Beta", "---", "Gamma", "---"],
"tpl_has_template_tag": False,
"nested": [["A1", "A2"], ["B1", "B2"]],
}
cases.append({"name": "vfor_array_index_and_template", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: Object iteration (value / value,key / value,key,index)
c2 = page.evaluate("""() => ({
val: Array.from(document.querySelectorAll('#obj-val-ul li')).map(el => el.textContent),
kv: Array.from(document.querySelectorAll('#obj-kv-ul li')).map(el => el.textContent),
kvi: Array.from(document.querySelectorAll('#obj-kvi-ul li')).map(el => el.textContent)
})""")
exp2 = {
"val": ["蓝色天空", "https://example.org", "掌握前端核心"],
"kv": ["name : 蓝色天空", "url : https://example.org", "slogan : 掌握前端核心"],
"kvi": ["0. name : 蓝色天空", "1. url : https://example.org", "2. slogan : 掌握前端核心"],
}
cases.append({"name": "vfor_object_value_key_index", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: Integer range 1..10 & computed evenNumbers
c3 = page.evaluate("""() => {
const ints = Array.from(document.querySelectorAll('#int-ul li')).map(el => el.textContent);
const evensBefore = Array.from(document.querySelectorAll('#even-ul li')).map(el => el.textContent);
window.__pushNum(8);
const evensAfter = Array.from(document.querySelectorAll('#even-ul li')).map(el => el.textContent);
return { int_count: ints.length, int_first: ints[0], int_last: ints[ints.length - 1], evens_before: evensBefore, evens_after: evensAfter };
}""")
exp3 = {
"int_count": 10,
"int_first": "1",
"int_last": "10",
"evens_before": ["2", "4", "6"],
"evens_after": ["2", "4", "6", "8"],
}
cases.append({"name": "vfor_integer_and_computed_filter", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: <template v-for> + v-if inside <select>
init_sel = page.evaluate("() => ({ val: document.getElementById('site-select').value, out: document.getElementById('sel-out').textContent })")
page.select_option("#site-select", "Gamma")
after_sel = page.evaluate("() => ({ val: document.getElementById('site-select').value, out: document.getElementById('sel-out').textContent })")
c4 = {"init": init_sel, "after_select": after_sel}
exp4 = {
"init": {"val": "Beta", "out": "您选中了:Beta"},
"after_select": {"val": "Gamma", "out": "您选中了:Gamma"},
}
cases.append({"name": "vfor_template_with_vif_select", "passed": c4 == exp4, "expected": exp4, "actual": c4})
# Case 5: Component v-for todo list (add & @remove)
snap_todos = "() => Array.from(document.querySelectorAll('#todo-ul li')).map(li => li.dataset.key + ':' + li.querySelector('.todo-title').textContent)"
t_init = page.evaluate(snap_todos)
page.fill("#new-todo", "学习组件循环")
page.click("#btn-add-todo")
t_added = page.evaluate(snap_todos)
input_cleared = page.evaluate("() => document.getElementById('new-todo').value === ''")
page.locator("#todo-ul li .btn-rm").first.click()
t_removed = page.evaluate(snap_todos)
c5 = {"init": t_init, "after_add": t_added, "input_cleared": input_cleared, "after_remove_first": t_removed}
exp5 = {
"init": ["1:阅读 Vue3 文档", "2:编写列表组件"],
"after_add": ["1:阅读 Vue3 文档", "2:编写列表组件", "3:学习组件循环"],
"input_cleared": True,
"after_remove_first": ["2:编写列表组件", "3:学习组件循环"],
}
cases.append({"name": "vfor_component_todo_list", "passed": c5 == exp5, "expected": exp5, "actual": c5})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对数组索引与 template/嵌套渲染、对象三形态迭代、1..10 范围与偶数过滤追加、select 默认 Beta 切 Gamma,以及 Todo 表单新增与 @remove 删除。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:0a89924b9f20c5f559063446d15a8cd9c18de77367e390e566bf4b4db94c1a42
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:888d4c8b46e44206c989b49023669b3197971666f3fca4f870bf2fd47352c415
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Vue 3 中为什么不建议把 v-for 和 v-if 写在同一个元素上,应该怎样改写?
展开参考解答
Vue 3 中同一节点上 v-if 优先级高于 v-for,导致 v-if 表达式无法访问 v-for 定义的循环变量;应改用计算属性预先过滤列表,或将 v-for 移至外层 <template> 再在内层节点写 v-if。