蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 本地 HTTP 服务实测生命周期钩子顺序与 fetch('/posts.json') 四态切换

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-blog-lifecycle-fetch.py
explore-blog-lifecycle-fetch.py337 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/vue3-blog-lifecycle-fetch-lab/explore-blog-lifecycle-fetch.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-blog-lifecycle-fetch.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vue3

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip

下载课程关联工程包:Vue3

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a805.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习