蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue3 · 本地阅读预览
教程 / 前端开发 / Vue3

模板语法渲染

系统掌握插值表达式 {{ }}、属性绑定 v-bind/:、列表渲染 v-for 与 :key 稳定性、条件渲染 v-if/v-else 与 v-show 差异,并在 Chromium 中实测博客首页卡片网格与 key 复用陷阱。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

插值表达式 {{ }} 与属性绑定 v-bind

模板语法用于把 JavaScript 数据声明式渲染为博客页面。插值表达式 `{{ }}` 将变量、算术/三元运算或函数调用结果输出到标签文本中(不可写 `if`、`for` 等语句),且仅替换文本内容、自动转义标签字符而不破坏外层元素。本站 Chromium 实测渲染标题“蓝色天空前端笔记”、作者“作者:小明”、日期“当前时间:2024/5/15”,并确认插值输出 `<strong>原样文本</strong>` 时不会生成 `<strong>` 子节点。

HTML 属性不能使用双花括号,而应使用 `v-bind:属性名` 或实际开发中最常用的冒号简写(`:src`、`:alt`、`:href`),动态类名还支持对象语法 `:class="{ active: isActive, 'text-bold': true }"`。本站实测验证图片 `alt="文章封面"`、链接 `href="/post/1"` 且目标元素同时具备 `['active', 'text-bold']` 两个类名。

列表渲染 v-for 与 :key 的稳定性陷阱

博客首页文章集合以对象数组组织,通过 `v-for="article in articles" :key="article.id"` 循环生成带封面、分类徽章、标题、摘要与日期的文章卡片,配合 CSS Grid(`repeat(auto-fill, minmax(280px, 1fr))`)自适应排布。

`:key` 是 Vue 追踪节点身份的核心依据,应始终绑定唯一且稳定的业务 ID,切忌用数组下标 `index`。本站 Chromium 对照实验实测:在两条带输入框的列表首项键入“Vue笔记”后,向数组头部插入新文章 `id=99`——以 `article.id` 为 key 的列表准确把“Vue笔记”留在原 `id=1` 项(移至第 2 位),而以 `index` 为 key 的列表却将“Vue笔记”错留在新插入的 `id=99` 项上。

条件渲染 v-if / v-show 与完整博客首页整合

`v-if`、`v-else-if`、`v-else` 可清晰表达异步加载的三种典型状态:加载中、有文章列表、空数据提示。与 `v-show` 相比,`v-if` 真正增删 DOM 节点,适合条件稳定的场景;`v-show` 仅切换 `display: none`,适合高频切换的标签页。本站 Chromium 实测验证三态依次呈现“加载中,请稍候...” -> `2` 张卡片 -> “还没有文章,敬请期待。”;同时核对条件为假时 `v-if` 节点已从 DOM 移除(`exists=false`),而 `v-show` 节点仍在 DOM 中且计算样式 `display === 'none'`。

将 `{{ }}`、`:bind`、`v-for` 与 `v-if/v-else` 整合即可完成数据驱动的博客首页组件。本站 Chromium 实测最终首页网格:`display` 为 `grid`,准确渲染 `3` 张 `.article-card` 卡片,分类徽章依次为 `['Vue', 'JavaScript', 'CSS']`(前景色 `rgb(66, 184, 131)`、底色 `rgb(232, 245, 233)`),发布日期依次为 `['2024-05-10', '2024-05-08', '2024-05-05']`。

v-for 中 :key 不同取值的行为与后果

key 的取值后果
唯一的 id(推荐)Vue 可准确追踪每条数据对应的 DOM,复用与局部更新均安全高效
数组下标 index头部插入、删除或重排时下标位移,易导致输入框等局部状态错位
不写 key触发开发警告,默认采用就地更新策略,有状态子项易错乱且复用受限

v-if 与 v-show 渲染机制对比

指令切换方式初始渲染成本切换成本适用场景
v-if动态创建或销毁 DOM 节点低(条件为假时不渲染)高(每次切换重建 DOM)权限控制、加载态切换等低频变更场景
v-show仅切换元素的 CSS display 属性高(无论真假都会先渲染)低(仅修改样式)标签页、折叠面板等高频显隐切换场景

实测博客模板插值、动态属性绑定、v-for id/index 键状态对比与 v-if/v-show 差异

python · 阅读源码
"""Offline Playwright Chromium lab for Vue3 Ch40: Blog template syntax rendering."""
import json
from playwright.sync_api import sync_playwright

HTML = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>Vue3 Blog Template Syntax Lab</title>
<style>
  body { font-family: system-ui, sans-serif; margin: 0; background: #f5f5f5; color: #333; }
  .home { max-width: 960px; margin: 0 auto; padding: 20px; }
  .article-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 24px; }
  .article-card { background: #fff; border-radius: 12px; overflow: hidden; }
  .card-category { display: inline-block; padding: 2px 10px; background: #e8f5e9; color: #42b883; border-radius: 12px; font-size: 12px; }
  .card-cover { width: 100%; height: 120px; object-fit: cover; display: block; }
  .active { border: 1px solid #42b883; }
  .text-bold { font-weight: 700; }
</style>
</head>
<body>
  <section id="sec-mustache">
    <h1 id="m-title"></h1>
    <p id="m-author"></p>
    <p id="m-date"></p>
    <p id="m-escape"></p>
  </section>

  <section id="sec-vbind">
    <img id="b-img" />
    <a id="b-link">阅读全文</a>
    <div id="b-box">动态 class 测试</div>
  </section>

  <section class="home" id="sec-home">
    <h2 class="section-title">最新文章</h2>
    <div id="home-body"></div>
  </section>

  <section id="sec-key-demo">
    <div id="list-by-id"></div>
    <div id="list-by-index"></div>
  </section>

  <section id="sec-cond">
    <div id="state-host"></div>
    <div id="vif-host"></div>
    <div id="vshow-box">v-show 面板</div>
  </section>

<script>
// Inline SVG data URI so zero external requests are made
const SVG_COVER = 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="300" height="120"><rect width="300" height="120" fill="#e8f5e9"/></svg>');

function formatCnDate(iso) {
  const [y, m, d] = iso.split('-');
  return `${y}/${Number(m)}/${Number(d)}`;
}

// 1. Mustache {{ }} interpolation (textContent only, safe escaping) + v-bind
const blogTitle = '蓝色天空前端笔记';
const author = '小明';
const rawSnippet = '<strong>原样文本</strong>';
document.getElementById('m-title').textContent = blogTitle;
document.getElementById('m-author').textContent = `作者:${author}`;
document.getElementById('m-date').textContent = `当前时间:${formatCnDate('2024-05-15')}`;
document.getElementById('m-escape').textContent = rawSnippet;

const coverUrl = SVG_COVER;
const linkUrl = '/post/1';
const isActive = true;
const imgEl = document.getElementById('b-img');
imgEl.setAttribute('src', coverUrl);
imgEl.setAttribute('alt', '文章封面');
document.getElementById('b-link').setAttribute('href', linkUrl);
const boxEl = document.getElementById('b-box');
const classMap = { active: isActive, 'text-bold': true };
for (const [cls, on] of Object.entries(classMap)) boxEl.classList.toggle(cls, Boolean(on));

// 2. Complete blog homepage v-for + v-if/v-else
const articles = [
  { id: 1, title: 'Vue3 入门完全指南', summary: '组合式 API 核心概念。', date: '2024-05-10', category: 'Vue', cover: SVG_COVER },
  { id: 2, title: 'JavaScript 异步编程详解', summary: 'Promise、async/await 与事件循环。', date: '2024-05-08', category: 'JavaScript', cover: SVG_COVER },
  { id: 3, title: 'CSS Grid 布局实战', summary: '响应式网格布局实践。', date: '2024-05-05', category: 'CSS', cover: SVG_COVER }
];

function renderHome(list) {
  const host = document.getElementById('home-body');
  if (!list.length) {
    host.innerHTML = '<p class="empty-tip">还没有文章,敬请期待。</p>';
    return;
  }
  const grid = document.createElement('div');
  grid.className = 'article-grid';
  for (const a of list) {
    const card = document.createElement('div');
    card.className = 'article-card';
    card.dataset.key = String(a.id);
    card.innerHTML = `
      <img src="${a.cover}" alt="${a.title}" class="card-cover" />
      <div class="card-content">
        <span class="card-category">${a.category}</span>
        <h3 class="card-title">${a.title}</h3>
        <p class="card-summary">${a.summary}</p>
        <span class="card-date">${a.date}</span>
      </div>`;
    grid.appendChild(card);
  }
  host.innerHTML = '';
  host.appendChild(grid);
}
renderHome(articles);

// 3. v-for key=id vs key=index DOM reuse comparison
let keyItems = [
  { id: 1, title: 'Vue3 入门' },
  { id: 2, title: 'CSS 布局' }
];
const idNodes = new Map();
const idxNodes = new Map();

function patchList(containerId, cache, mode) {
  const host = document.getElementById(containerId);
  const frag = document.createDocumentFragment();
  keyItems.forEach((item, idx) => {
    const k = mode === 'id' ? String(item.id) : String(idx);
    let row = cache.get(k);
    if (!row) {
      row = document.createElement('div');
      row.className = 'k-row';
      const label = document.createElement('span');
      const inp = document.createElement('input');
      row.append(label, inp);
      cache.set(k, row);
    }
    row.dataset.itemId = String(item.id);
    row.querySelector('span').textContent = item.title;
    frag.appendChild(row);
  });
  host.innerHTML = '';
  host.appendChild(frag);
}
patchList('list-by-id', idNodes, 'id');
patchList('list-by-index', idxNodes, 'index');

window.__prependAndCheckKeys = function() {
  document.querySelector('#list-by-id .k-row input').value = 'Vue笔记';
  document.querySelector('#list-by-index .k-row input').value = 'Vue笔记';
  keyItems = [{ id: 99, title: '置顶新文' }, ...keyItems];
  patchList('list-by-id', idNodes, 'id');
  patchList('list-by-index', idxNodes, 'index');
  const idList = [...document.querySelectorAll('#list-by-id .k-row')].map(r => ({
    id: Number(r.dataset.itemId),
    inputVal: r.querySelector('input').value
  }));
  const idxList = [...document.querySelectorAll('#list-by-index .k-row')].map(r => ({
    id: Number(r.dataset.itemId),
    inputVal: r.querySelector('input').value
  }));
  return { idList, idxList };
};

// 4. v-if / v-else-if / v-else 3-state UI & v-if vs v-show
window.__testConditional = function() {
  const host = document.getElementById('state-host');
  function renderState(isLoading, items) {
    if (isLoading) host.innerHTML = '<p class="st">加载中,请稍候...</p>';
    else if (items.length > 0) host.innerHTML = `<div class="st">${items.map(x => `<div class="mini-card">${x.title}</div>`).join('')}</div>`;
    else host.innerHTML = '<p class="st">还没有文章,敬请期待。</p>';
  }
  renderState(true, []);
  const s1 = host.textContent.trim();
  renderState(false, [{ id: 1, title: 'Vue3 入门' }, { id: 2, title: 'React 对比' }]);
  const s2Count = host.querySelectorAll('.mini-card').length;
  renderState(false, []);
  const s3 = host.textContent.trim();

  // v-if=false removes DOM node; v-show=false keeps DOM node with display:none
  const vifHost = document.getElementById('vif-host');
  vifHost.innerHTML = '<div id="vif-box">v-if 面板</div>';
  vifHost.innerHTML = ''; // toggled to false
  const vshowBox = document.getElementById('vshow-box');
  vshowBox.style.display = 'none';

  return {
    loadingText: s1,
    loadedCardCount: s2Count,
    emptyText: s3,
    vifNodeExistsWhenFalse: document.getElementById('vif-box') !== null,
    vshowNodeExistsWhenFalse: document.getElementById('vshow-box') !== null,
    vshowDisplayWhenFalse: getComputedStyle(vshowBox).display
  };
};
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1280, "height": 800})
        page.set_content(HTML, wait_until="domcontentloaded")

        # Case 1: Mustache {{ }} interpolation & v-bind / : attribute binding
        act1 = page.evaluate("""() => ({
            title: document.getElementById('m-title').textContent,
            author: document.getElementById('m-author').textContent,
            date: document.getElementById('m-date').textContent,
            escapedHtmlHasStrongChild: document.querySelector('#m-escape strong') !== null,
            escapedText: document.getElementById('m-escape').textContent,
            imgAlt: document.getElementById('b-img').getAttribute('alt'),
            linkHref: document.getElementById('b-link').getAttribute('href'),
            boxClasses: [...document.getElementById('b-box').classList].sort()
        })""")
        exp1 = {
            "title": "蓝色天空前端笔记",
            "author": "作者:小明",
            "date": "当前时间:2024/5/15",
            "escapedHtmlHasStrongChild": False,
            "escapedText": "<strong>原样文本</strong>",
            "imgAlt": "文章封面",
            "linkHref": "/post/1",
            "boxClasses": ["active", "text-bold"],
        }
        cases.append({"name": "interpolation_and_vbind_attrs", "expected": exp1, "actual": act1, "passed": act1 == exp1})

        # Case 2: Complete blog homepage v-for cards, categories, dates, CSS Grid
        act2 = page.evaluate("""() => {
            const grid = document.querySelector('.article-grid');
            const badge = document.querySelector('.card-category');
            return {
                gridDisplay: getComputedStyle(grid).display,
                cardCount: document.querySelectorAll('.article-card').length,
                categories: [...document.querySelectorAll('.card-category')].map(el => el.textContent),
                dates: [...document.querySelectorAll('.card-date')].map(el => el.textContent),
                badgeColor: getComputedStyle(badge).color,
                badgeBg: getComputedStyle(badge).backgroundColor
            };
        }""")
        exp2 = {
            "gridDisplay": "grid",
            "cardCount": 3,
            "categories": ["Vue", "JavaScript", "CSS"],
            "dates": ["2024-05-10", "2024-05-08", "2024-05-05"],
            "badgeColor": "rgb(66, 184, 131)",
            "badgeBg": "rgb(232, 245, 233)",
        }
        cases.append({"name": "vfor_blog_homepage_cards", "expected": exp2, "actual": act2, "passed": act2 == exp2})

        # Case 3: v-for :key="article.id" vs index state preservation
        act3 = page.evaluate("window.__prependAndCheckKeys()")
        exp3 = {
            "idList": [
                {"id": 99, "inputVal": ""},
                {"id": 1, "inputVal": "Vue笔记"},
                {"id": 2, "inputVal": ""},
            ],
            "idxList": [
                {"id": 99, "inputVal": "Vue笔记"},
                {"id": 1, "inputVal": ""},
                {"id": 2, "inputVal": ""},
            ],
        }
        cases.append({"name": "vfor_key_id_vs_index_state", "expected": exp3, "actual": act3, "passed": act3 == exp3})

        # Case 4: v-if/v-else-if/v-else 3-state flow & v-if vs v-show DOM check
        act4 = page.evaluate("window.__testConditional()")
        exp4 = {
            "loadingText": "加载中,请稍候...",
            "loadedCardCount": 2,
            "emptyText": "还没有文章,敬请期待。",
            "vifNodeExistsWhenFalse": False,
            "vshowNodeExistsWhenFalse": True,
            "vshowDisplayWhenFalse": "none",
        }
        cases.append({"name": "vif_three_states_and_vshow_dom", "expected": exp4, "actual": act4, "passed": act4 == exp4})

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对文本转义与动态 class 绑定、3 张博客卡片网格与徽章样式、头部插入时 id 键保留输入框状态而 index 键发生错位,以及三态条件切换与 v-if/v-show DOM 差异。
实测博客模板插值、动态属性绑定、v-for id/index 键状态对比与 v-if/v-show 差异

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:8b433e4516b02b350e9fba8940664c6f98842988f4fa50e3cc5b874588caf626

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载模板语法渲染实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:247af37f7a8cb1aedfeb422ed298d21c3d846ac0f6e3c0cabad197aa87c1adfa

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在 v-for 渲染含输入框的列表时,用数组下标 index 做 :key 会在头部插入新元素后导致输入内容串行?

展开参考解答

头部插入后原下标 0 的元素移到了下标 1,而新元素占据了下标 0;Vue 按 key=0 复用旧的 DOM 节点,导致原本填在旧项输入框中的非受控 DOM 状态被留在了新插入的第 0 项上。

规范与官方依据