生命周期与数据请求
核对 Vue 3 生命周期钩子全流程、onMounted 注册规则、public/posts.json 静态资源与真实 fetch() 异步请求四态 UI(加载/成功/失败重试/空数据)离线 Chromium 实测。
学完这一章,你能够
- 核对 Vue 3 生命周期钩子全流程、onMounted 注册规则、public/posts.json 静态资源与真实 fetch() 异步请求四态 UI(加载/成功/失败重试/空数据)离线 Chromium 实测。
组件生命周期概念与钩子调用顺序
每个 Vue 组件从创建、挂载、更新到卸载都会依次经过固定阶段,称为生命周期。Vue 在关键节点提供组合式钩子函数(`setup()`、`onBeforeMount`、`onMounted`、`onBeforeUpdate`、`onUpdated`、`onBeforeUnmount`、`onUnmounted`),其中博客项目最常用的是 `onMounted`——在 DOM 挂载完毕后发起数据请求。务必注意:所有生命周期钩子都必须在 `<script setup>` 顶层同步注册,切勿放入异步 `await` 之后或条件分支内部,否则 Vue 无法将其绑定到当前组件实例。
同一组件内允许按功能多次调用 `onMounted`,它们会严格按照注册先后依次执行;同时在 `onBeforeUnmount` 中清除定时器、取消订阅或移除事件监听可有效防止内存泄漏。本站离线 Chromium 实测完整生命周期序列精确输出 `['setup', 'onBeforeMount', 'onMounted#1', 'onMounted#2', 'onBeforeUpdate', 'onUpdated', 'onBeforeUnmount', 'onUnmounted']`,两次 `onMounted` 按序执行并将展示文本更新为 `数据加载完成!`,卸载阶段成功清理定时器。
public/posts.json 与 onMounted 异步 fetch 实战
为了模拟真实前后端分离加载流程,可将文章列表保存为 `public/posts.json`。Vite 会将 `public/` 目录下的文件原样提供静态服务并在打包时直接复制到构建根目录,因此浏览器中可直接 `fetch('/posts.json')` 获取。在 `HomeView.vue` 中声明 `articles`、`isLoading`、`error` 三个响应式状态,于 `onMounted` 内调用 `async function fetchPosts()`:由于 `fetch()` 遇到 HTTP 404/500 不会自动 reject,必须手动检查 `if (!response.ok) throw new Error(...)`,并在 `finally` 中复位 `isLoading.value = false`。本站通过本地 `127.0.0.1` 回环服务器延迟 150ms 返回 `/posts.json` 实测:响应到达前 DOM 显示 `加载中,请稍候...`,响应成功后自动渲染 3 张文章卡片(`Vue3 入门完全指南`、`JavaScript 异步编程详解`、`CSS Grid 布局实战`)。
异步请求四种 UI 状态与详情页复用
健壮的异步页面应当完整覆盖加载中、成功、失败重试以及空数据四种 UI 状态:请求中显示 loading 或骨架屏,成功渲染列表,网络或服务端异常时呈现错误文案与重试按钮,返回空数组时给出友好占位提示而非白屏。本站实测服务端返回 HTTP 500 时页面展示含 `HTTP 500` 的错误提示与重试按钮,点击 `#btn-retry` 重新请求 `/posts.json` 后恢复渲染 `3` 篇文章;返回 `[]` 时页面准确展示 `还没有文章,敬请期待。`。
详情页 `PostView.vue` 同样可在 `onMounted` 中异步请求 `/posts.json`,再借助 `computed(() => posts.value.find(p => p.id === id))` 按路由 ID 定位当前文章并处理加载、错误与不存在分支。本站实测详情页异步加载 `id = 2` 成功渲染标题 `JavaScript 异步编程详解` 与正文小节 `什么是异步?`,请求不存在的 `id = 99` 则展示 `文章不存在`。
Vue 3 组合式生命周期钩子总览
| 钩子函数 | 执行时机 | 典型使用场景 |
|---|---|---|
| setup() / <script setup> | 组件实例初始化阶段最早执行 | 声明 ref/reactive 状态、computed 与事件处理函数 |
| onBeforeMount | 模板编译完成、真实 DOM 挂载之前 | 极少直接使用,用于挂载前最后状态准备 |
| onMounted | 组件已挂载到真实 DOM 之后 | 发起 fetch 数据请求、初始化图表等第三方库、获取模板引用 |
| onBeforeUpdate | 响应式数据变更后、DOM 打补丁之前 | 较少使用,适合在重渲染前读取旧 DOM 状态 |
| onUpdated | 响应式变更引发的 DOM 更新完成之后 | 依赖最新 DOM 布局的测量或滚动位置调整 |
| onBeforeUnmount | 组件实例即将卸载销毁之前 | 清理定时器、取消请求/订阅、解绑全局事件监听 |
| onUnmounted | 组件完全卸载且子组件均已销毁之后 | 释放残留句柄与卸载完成日志确认 |
异步数据请求核心 UI 状态对照
| 状态 | 出现时机 | 推荐 UI 表现 |
|---|---|---|
| Loading(加载中) | 请求已发出但尚未收到服务端响应期间 | 展示加载动画、文案提示或骨架屏占位 |
| Success(加载成功) | 响应状态正常且成功解析 JSON 数据(空数组可单列空态提示) | 渲染正常文章列表或详情内容 |
| Error(请求失败) | 网络断开、跨域受阻或服务端返回 4xx/5xx 异常状态 | 展示明确错误信息并提供可再次触发请求的“重试”按钮 |
离线 Chromium 本地 HTTP 服务实测生命周期钩子顺序与 fetch('/posts.json') 四态切换
"""Offline Playwright Chromium lab for Vue 3 Ch 44: lifecycle hooks & real fetch() async states."""
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
POSTS_DATA = [
{
"id": 1,
"title": "Vue3 入门完全指南",
"summary": "从零开始学习 Vue3 组合式 API,涵盖 ref、reactive、computed 等核心概念。",
"content": "<h2>为什么学 Vue3?</h2><p>Vue3 是目前最流行的前端框架之一。</p>",
"category": "Vue",
"date": "2024-05-10",
},
{
"id": 2,
"title": "JavaScript 异步编程详解",
"summary": "一文搞懂 Promise、async/await、事件循环与微任务队列。",
"content": "<h2>什么是异步?</h2><p>JS 是单线程的,异步避免主线程阻塞。</p>",
"category": "JavaScript",
"date": "2024-05-08",
},
{
"id": 3,
"title": "CSS Grid 布局实战",
"summary": "用 CSS Grid 轻松实现复杂的响应式布局。",
"content": "<h2>Grid 入门</h2><p>Grid 是二维布局系统。</p>",
"category": "CSS",
"date": "2024-05-05",
},
]
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Lifecycle & Fetch Lab</title>
</head>
<body>
<section id="lifecycle-box"></section>
<section id="home-view"></section>
<section id="post-view"></section>
<script>
const lifecycleLog = [];
let activeTimerCleaned = false;
// 1. Simulate full component lifecycle hooks order + multiple onMounted + unmount cleanup
function runLifecycleDemo() {
const hooks = { beforeMount: [], mounted: [], beforeUpdate: [], updated: [], beforeUnmount: [], unmounted: [] };
const onBeforeMount = (fn) => hooks.beforeMount.push(fn);
const onMounted = (fn) => hooks.mounted.push(fn);
const onBeforeUpdate = (fn) => hooks.beforeUpdate.push(fn);
const onUpdated = (fn) => hooks.updated.push(fn);
const onBeforeUnmount = (fn) => hooks.beforeUnmount.push(fn);
const onUnmounted = (fn) => hooks.unmounted.push(fn);
// setup() runs first
lifecycleLog.push('setup');
let msg = '加载中...';
let timerId = null;
onBeforeMount(() => lifecycleLog.push('onBeforeMount'));
onMounted(() => {
lifecycleLog.push('onMounted#1');
timerId = setInterval(() => {}, 10000);
});
onMounted(() => {
lifecycleLog.push('onMounted#2');
msg = '数据加载完成!';
});
onBeforeUpdate(() => lifecycleLog.push('onBeforeUpdate'));
onUpdated(() => lifecycleLog.push('onUpdated'));
onBeforeUnmount(() => {
lifecycleLog.push('onBeforeUnmount');
if (timerId !== null) {
clearInterval(timerId);
activeTimerCleaned = true;
}
});
onUnmounted(() => lifecycleLog.push('onUnmounted'));
// Mount phase
hooks.beforeMount.forEach((fn) => fn());
const box = document.getElementById('lifecycle-box');
box.textContent = msg;
hooks.mounted.forEach((fn) => fn());
// Update phase
hooks.beforeUpdate.forEach((fn) => fn());
box.textContent = msg;
hooks.updated.forEach((fn) => fn());
// Unmount phase
hooks.beforeUnmount.forEach((fn) => fn());
const finalMsgBeforeUnmount = box.textContent;
box.textContent = '';
hooks.unmounted.forEach((fn) => fn());
return { lifecycleLog, finalMsgBeforeUnmount, activeTimerCleaned };
}
// 2. Real fetch('/posts.json') with loading / success / error + retry / empty UI states
async function loadHome(endpoint) {
const el = document.getElementById('home-view');
const state = { isLoading: true, error: null, articles: [] };
const render = () => {
if (state.isLoading) {
el.innerHTML = '<p class="status-msg loading">加载中,请稍候...</p>';
} else if (state.error) {
el.innerHTML = `<p class="status-msg error">加载失败:${state.error}<button id="btn-retry">重试</button></p>`;
document.getElementById('btn-retry').addEventListener('click', () => loadHome('/posts.json'));
} else if (state.articles.length === 0) {
el.innerHTML = '<p class="status-msg empty">还没有文章,敬请期待。</p>';
} else {
el.innerHTML = `<div class="article-grid">${state.articles
.map((a) => `<div class="card"><h3>${a.title}</h3><span>${a.category}</span></div>`)
.join('')}</div>`;
}
};
render();
try {
const res = await fetch(endpoint);
if (!res.ok) throw new Error(`加载失败:HTTP ${res.status}`);
state.articles = await res.json();
} catch (err) {
state.error = err.message;
} finally {
state.isLoading = false;
render();
}
}
// 3. PostView async fetch lookup by ID
async function loadPostDetail(targetId) {
const el = document.getElementById('post-view');
el.innerHTML = '<p class="post-loading">加载中...</p>';
try {
const res = await fetch('/posts.json');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const posts = await res.json();
const article = posts.find((p) => p.id === Number(targetId));
if (!article) {
el.innerHTML = '<div class="post-not-found"><h2>文章不存在</h2></div>';
} else {
el.innerHTML = `<article><h1>${article.title}</h1><span class="cat">${article.category}</span><div class="content">${article.content}</div></article>`;
}
} catch (err) {
el.innerHTML = `<p class="post-error">${err.message}</p>`;
}
}
window.__fetchLab = {
runLifecycleDemo,
loadHome,
loadPostDetail
};
</script>
</body>
</html>
"""
class PostsHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
qs = parse_qs(parsed.query)
mode = qs.get("mode", ["ok"])[0]
if parsed.path == "/":
body = HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
if parsed.path == "/posts.json":
if mode == "slow":
self.server.slow_gate.wait(timeout=5.0)
elif mode == "error500":
body = b'{"error":"internal"}'
self.send_response(500)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
elif mode == "empty":
body = b"[]"
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
body = json.dumps(POSTS_DATA, ensure_ascii=False).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
pass
def main():
server = HTTPServer(("127.0.0.1", 0), PostsHandler)
server.slow_gate = threading.Event()
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base_url = f"http://127.0.0.1:{port}"
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
page.goto(f"{base_url}/")
# Case 1: Lifecycle hook order & cleanup
lc = page.evaluate("window.__fetchLab.runLifecycleDemo()")
# Case 2: Slow fetch -> observe real loading UI -> success cards
page.evaluate("() => { window.__slowPromise = window.__fetchLab.loadHome('/posts.json?mode=slow'); }")
page.wait_for_selector("#home-view .loading")
loading_text = page.text_content("#home-view .loading")
server.slow_gate.set()
page.evaluate("() => window.__slowPromise")
page.wait_for_selector("#home-view .card")
loaded_titles = page.eval_on_selector_all("#home-view .card h3", "els => els.map(e => e.textContent)")
# Case 3: HTTP 500 error -> click Retry -> success, plus empty []
page.evaluate("() => window.__fetchLab.loadHome('/posts.json?mode=error500')")
page.wait_for_selector("#home-view .error")
error_text = page.text_content("#home-view .error")
page.click("#btn-retry")
page.wait_for_selector("#home-view .card")
retry_count = page.locator("#home-view .card").count()
page.evaluate("() => window.__fetchLab.loadHome('/posts.json?mode=empty')")
page.wait_for_selector("#home-view .empty")
empty_text = page.text_content("#home-view .empty")
# Case 4: PostView async fetch lookup (id=2 found, id=99 not found)
page.evaluate("() => window.__fetchLab.loadPostDetail(2)")
page.wait_for_selector("#post-view article h1")
post2_title = page.text_content("#post-view article h1")
post2_h2 = page.text_content("#post-view .content h2")
page.evaluate("() => window.__fetchLab.loadPostDetail(99)")
page.wait_for_selector("#post-view .post-not-found")
post99_h2 = page.text_content("#post-view .post-not-found h2")
finally:
browser.close()
finally:
server.shutdown()
server.server_close()
actuals = {
"lifecycle_hooks_order_and_multi_mounted": {
"order": lc["lifecycleLog"],
"mounted_msg": lc["finalMsgBeforeUnmount"],
"timer_cleaned": lc["activeTimerCleaned"],
},
"onmounted_fetch_loading_to_success": {
"loading_text": loading_text,
"loaded_count": len(loaded_titles),
"loaded_titles": loaded_titles,
},
"fetch_http500_retry_and_empty_state": {
"error_contains_500": "HTTP 500" in error_text,
"retry_restored_count": retry_count,
"empty_text": empty_text,
},
"post_view_async_fetch_lookup": {
"post2_title": post2_title,
"post2_h2": post2_h2,
"post99_h2": post99_h2,
},
}
expected = {
"lifecycle_hooks_order_and_multi_mounted": {
"order": [
"setup",
"onBeforeMount",
"onMounted#1",
"onMounted#2",
"onBeforeUpdate",
"onUpdated",
"onBeforeUnmount",
"onUnmounted",
],
"mounted_msg": "数据加载完成!",
"timer_cleaned": True,
},
"onmounted_fetch_loading_to_success": {
"loading_text": "加载中,请稍候...",
"loaded_count": 3,
"loaded_titles": ["Vue3 入门完全指南", "JavaScript 异步编程详解", "CSS Grid 布局实战"],
},
"fetch_http500_retry_and_empty_state": {
"error_contains_500": True,
"retry_restored_count": 3,
"empty_text": "还没有文章,敬请期待。",
},
"post_view_async_fetch_lookup": {
"post2_title": "JavaScript 异步编程详解",
"post2_h2": "什么是异步?",
"post99_h2": "文章不存在",
},
}
cases = [
{"name": k, "expected": expected[k], "actual": actuals[k], "passed": actuals[k] == expected[k]}
for k in expected
]
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 8 步生命周期顺序与卸载清定时器、慢响应下加载态过渡到 3 张文章卡片、HTTP 500 报错点击重试恢复、空数组提示及详情页异步查找。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:33c3f73304dfecfb460334162a3b59f60055299e5668f4c04f0f9cc8f7ff7641
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:8665c64674931fceb0ba1d159da9a9ee05b6c040670df4915407849d519da840
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 fetch('/posts.json') 在服务端返回 HTTP 500 时仍需手动判断 response.ok?生命周期钩子为何不能写在 await 之后?
展开参考解答
Fetch API 仅在网络层中断或请求被阻止时 reject,404/500 仍会 resolve 并将 response.ok 置为 false,必须显式抛错才能进入 catch 错误分支;Vue 在同步执行 setup 期间维护当前激活组件上下文,await 之后的微任务已脱离该上下文导致钩子无法绑定组件。