Vue.js 循环语句
核对 Vue 2 列表渲染指令 v-for 的数组迭代、template 多节点循环、对象单/双/三参数遍历(值、键名、索引)及整数范围循环实测结果。
学完这一章,你能够
- 核对 Vue 2 列表渲染指令 v-for 的数组迭代、template 多节点循环、对象单/双/三参数遍历(值、键名、索引)及整数范围循环实测结果。
数组列表渲染与 template 分组循环
Vue 使用 `v-for` 指令基于数据源循环渲染列表,基本语法形如 `site in sites`,其中 `sites` 是源数据数组,`site` 为当前迭代元素的别名。在模板 `<li v-for="site in sites">{{ site.name }}</li>` 中,数组每一项都会生成对应列表节点。本站离线 Chromium 实测初始渲染出 `['Mbsky', 'Google', 'Taobao']` 3 项,向 `sites` 追加 `{ name: 'Vue' }` 并重新渲染后列表同步扩展为 4 项。
与 `v-if` 类似,若每次迭代需要同时输出多个同级节点(例如一条名称项配一条分隔线项),可以把 `v-for` 放在 `<template>` 标签上而不必额外套一层无意义的父元素。本站离线实测 3 条站点数据经 `<template v-for="site in sites">` 展开后,在 `<ul>` 下直接产出 6 个 `<li>` 节点,且 DOM 中保留的 `<template>` 元素数量为 `0`。
v-for 迭代对象属性(值、键名与索引)
`v-for` 同样支持遍历普通 JavaScript 对象的属性,并可按需声明一至三个参数:单参数 `value in object` 仅取属性值;双参数 `(value, key) in object` 同时获取属性值与键名;三参数 `(value, key, index) in object` 则进一步提供从 `0` 开始的遍历索引(底层依 `Object.keys()` 顺序遍历)。本站离线 Chromium 对 `{ name: '蓝色天空网', url: 'https://www.mbsky.com', slogan: '前端与工程实践' }` 实测三种写法:单参数依次输出 3 个属性值;双参数输出 `name : 蓝色天空网` 等键值项;三参数输出 `0. name : 蓝色天空网`、`1. url : https://www.mbsky.com`、`2. slogan : 前端与工程实践`。
v-for 迭代正整数范围
除了数组与对象,`v-for` 还可直接接收一个正整数(如 `n in 10`),此时模板会按从 `1` 到目标整数的闭区间重复渲染对应次数。本站离线 Chromium 实测 `<li v-for="n in 10">{{ n }}</li>` 生成 10 个 `<li>` 元素,首项为 `'1'`、末项为 `'10'`,完整序列为 `['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']`。
离线 Chromium 核验 v-for 数组、<template> 多节点、对象三参数与整数 1..10 迭代
"""Offline Playwright Chromium lab for Vue 2 Chapter 07 (vue-loop)."""
import json
from playwright.sync_api import sync_playwright
MINI_VUE2_FOR_JS = r"""
(function (global) {
function evalInScope(scope, expr) {
return new Function('with(this){ return (' + expr + '); }').call(scope);
}
function renderTextNodes(node, scope) {
if (node.nodeType === 3 && /\{\{(.+?)\}\}/.test(node.textContent)) {
node.textContent = node.textContent.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalInScope(scope, exp.trim()));
} else if (node.nodeType === 1) {
Array.from(node.childNodes).forEach(c => renderTextNodes(c, scope));
}
}
function parseVFor(exp) {
const [lhs, rhs] = exp.split(/\s+in\s+/).map(s => s.trim());
const clean = lhs.replace(/^\(|\)$/g, '');
const vars = clean.split(',').map(s => s.trim());
return { vars, sourceExpr: rhs };
}
class Vue {
constructor(options) {
this.$data = options.data || {};
this.$el = document.querySelector(options.el);
this._vForSpecs = [];
this._prepare(this.$el);
this.render();
}
_prepare(root) {
root.querySelectorAll('[v-for]').forEach(el => {
const exp = el.getAttribute('v-for');
el.removeAttribute('v-for');
const parsed = parseVFor(exp);
const anchor = document.createComment('v-for:' + exp);
const parent = el.parentNode;
parent.insertBefore(anchor, el);
parent.removeChild(el);
this._vForSpecs.push({
anchor,
parent,
templateEl: el,
isTemplateTag: el.tagName === 'TEMPLATE',
parsed,
mounted: []
});
});
}
render() {
for (const spec of this._vForSpecs) {
spec.mounted.forEach(n => { if (n.parentNode) n.parentNode.removeChild(n); });
spec.mounted = [];
const src = evalInScope(this.$data, spec.parsed.sourceExpr);
const entries = [];
if (typeof src === 'number') {
for (let n = 1; n <= src; n++) entries.push([n, n - 1, n - 1]);
} else if (Array.isArray(src)) {
src.forEach((v, idx) => entries.push([v, idx, idx]));
} else if (src && typeof src === 'object') {
Object.keys(src).forEach((k, idx) => entries.push([src[k], k, idx]));
}
const frag = document.createDocumentFragment();
for (const tuple of entries) {
const scope = Object.create(this.$data);
spec.parsed.vars.forEach((varName, vi) => { scope[varName] = tuple[vi]; });
const clones = spec.isTemplateTag
? Array.from(spec.templateEl.content.childNodes).map(n => n.cloneNode(true))
: [spec.templateEl.cloneNode(true)];
clones.forEach(node => {
renderTextNodes(node, scope);
frag.appendChild(node);
spec.mounted.push(node);
});
}
spec.parent.insertBefore(frag, spec.anchor.nextSibling);
}
}
}
global.Vue = Vue;
})(window);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue 2 循环语句 v-for 实验</title></head>
<body>
<div id="app">
<ol id="list-array">
<li v-for="site in sites">{{{{ site.name }}}}</li>
</ol>
<ul id="list-template">
<template v-for="site in sites">
<li>{{{{ site.name }}}}</li>
<li>--------------</li>
</template>
</ul>
<ul id="obj-val">
<li v-for="value in object">{{{{ value }}}}</li>
</ul>
<ul id="obj-kv">
<li v-for="(value, key) in object">{{{{ key }}}} : {{{{ value }}}}</li>
</ul>
<ul id="obj-kvi">
<li v-for="(value, key, index) in object">{{{{ index }}}}. {{{{ key }}}} : {{{{ value }}}}</li>
</ul>
<ul id="int-range">
<li v-for="n in 10">{{{{ n }}}}</li>
</ul>
</div>
<script>{MINI_VUE2_FOR_JS}</script>
<script>
window.vm = new Vue({{
el: '#app',
data: {{
sites: [
{{ name: 'Mbsky' }},
{{ name: 'Google' }},
{{ name: 'Taobao' }}
],
object: {{
name: '蓝色天空网',
url: 'https://www.mbsky.com',
slogan: '前端与工程实践'
}}
}}
}});
</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: Array v-for and push update
res1 = page.evaluate("""() => {
const initial = Array.from(document.querySelectorAll('#list-array li')).map(el => el.textContent.trim());
window.vm.$data.sites.push({ name: 'Vue' });
window.vm.render();
const afterPush = Array.from(document.querySelectorAll('#list-array li')).map(el => el.textContent.trim());
return { initial, after_push: afterPush };
}""")
exp1 = {
"initial": ["Mbsky", "Google", "Taobao"],
"after_push": ["Mbsky", "Google", "Taobao", "Vue"],
}
cases.append({
"name": "v_for_array_and_reactive_mutation",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: <template v-for> multi-node expansion
res2 = page.evaluate("""() => {
window.vm.$data.sites.pop();
window.vm.render();
const items = Array.from(document.querySelectorAll('#list-template li')).map(el => el.textContent.trim());
const templateTags = document.querySelectorAll('#list-template template').length;
return { items, count: items.length, template_tags_in_dom: templateTags };
}""")
exp2 = {
"items": ["Mbsky", "--------------", "Google", "--------------", "Taobao", "--------------"],
"count": 6,
"template_tags_in_dom": 0,
}
cases.append({
"name": "v_for_template_multi_node",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: Object iteration with 1, 2, and 3 parameters (value, key, index)
res3 = page.evaluate("""() => ({
values_only: Array.from(document.querySelectorAll('#obj-val li')).map(el => el.textContent.trim()),
key_and_val: Array.from(document.querySelectorAll('#obj-kv li')).map(el => el.textContent.trim()),
index_key_val: Array.from(document.querySelectorAll('#obj-kvi li')).map(el => el.textContent.trim())
})""")
exp3 = {
"values_only": ["蓝色天空网", "https://www.mbsky.com", "前端与工程实践"],
"key_and_val": [
"name : 蓝色天空网",
"url : https://www.mbsky.com",
"slogan : 前端与工程实践",
],
"index_key_val": [
"0. name : 蓝色天空网",
"1. url : https://www.mbsky.com",
"2. slogan : 前端与工程实践",
],
}
cases.append({
"name": "v_for_object_value_key_index",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
# Case 4: Integer range iteration (1..10)
res4 = page.evaluate("""() => {
const nums = Array.from(document.querySelectorAll('#int-range li')).map(el => el.textContent.trim());
return { count: nums.length, first: nums[0], last: nums[nums.length - 1], sequence: nums };
}""")
exp4 = {
"count": 10,
"first": "1",
"last": "10",
"sequence": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
}
cases.append({
"name": "v_for_integer_range",
"passed": res4 == exp4,
"expected": exp4,
"actual": res4,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对数组渲染与追加更新、template 展开 6 个 li 且无残留 template 标签、对象单/双/三参数输出及整数范围 1 到 10。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:20f72212532ee9bc350ba6df92673c218666a52a5adc53166b9051996d0c6942
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:f190923ef75120b177f4e1d41343d0e3b35b1ec9038e4bc24d8c2ef9e4a48a51
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 `v-for="(value, key, index) in object"` 中三个参数的位置顺序能否互换?迭代整数 `n in 10` 是从 0 还是从 1 开始?
展开参考解答
不能互换,Vue 规定第一参数恒为属性值 `value`、第二参数为键名 `key`、第三参数为从 0 起的索引 `index`;而整数范围迭代 `n in 10` 从 `1` 开始到 `10` 结束。