蓝色天空.知识 · 实践 · 创造
我的收藏
Vue3 教程目录 48章
Vue3 / LEARN BY DOING

watch 与搜索功能

核对 watch 三种数据源与 immediate 选项、watchEffect 自动依赖追踪、防抖搜索合并频繁输入,以及博客首页搜索与分类叠加过滤的离线 Chromium 实测。

学完这一章,你能够

  • 核对 watch 三种数据源与 immediate 选项、watchEffect 自动依赖追踪、防抖搜索合并频繁输入,以及博客首页搜索与分类叠加过滤的离线 Chromium 实测。

何时使用 watch 与精确监听语法

模板响应式绑定适合把数据自动映射到视图,但当状态变化需要主动执行副作用——例如输入关键词过滤或拉取接口、切换分类时同步更新 `document.title`、把偏好写入 `localStorage` 或实时校验表单字段——就需要使用侦听器 `watch` 与 `watchEffect`。

`watch(source, (newVal, oldVal) => ...)` 显式指定被监听的数据源,并向回调提供新值与旧值以便对比处理。数据源支持三种常见形态:直接传入单个 `ref`、传入返回 `reactive` 属性的 getter 函数 `() => user.name`,以及传入多源数组 `[keyword, category]`。默认情况下 `watch` 采用懒执行策略,初始赋值不触发回调;若希望初始化立即运行一次,可附加 `{ immediate: true }`。本站离线 Chromium 实测:懒监听初始触发 `0` 次、配 `immediate` 初始触发 `1` 次;修改 `kw1` 为 `'Vue'` 时 `document.title` 更新为 `搜索:Vue` 且收到 `['', 'Vue']`;修改 `user.name` 捕获 `['小明', '小华']`;多源监听准确记录关键词与分类两次新旧元组变更。

watchEffect 自动追踪与选型对比

`watchEffect` 无需手动列举依赖项,会在创建时立即执行一次回调,并自动收集回调内部读取过的所有响应式状态,此后任一依赖变化均重新触发,但无法访问旧值。选型经验十分清晰:凡是能够由已有状态纯计算派生出的结果(如过滤后的文章列表),应优先使用带缓存的 `computed`;需要比较新旧值或精准控制副作用执行时机时用 `watch`;不关心旧值且希望初始化即自动响应多个依赖时用 `watchEffect`。本站实测 `watchEffect` 注册即产出初始长度 `2`,将 `effKeyword` 设为 `'Vue3'` 后缩减为 `1`(仅剩 `['Vue3 入门']`),清空后恢复 `2`。

防抖思路与博客搜索+分类叠加过滤实战

若搜索框每次敲击按键都触发远程接口请求,会造成大量无效开销。防抖(Debounce)通过在 `watch` 回调内先 `clearTimeout(timer)` 再重设延时定时器(如 `300ms`),确保用户停顿片刻后再执行过滤或请求。本地内存数据量小时防抖并非强制,但在真实后端检索场景至关重要。本站离线 Chromium 实测连续快速键入 `'V'`、`'Vu'`、`'Vue3'` 三次输入,180ms 防抖窗口将其合并为仅执行 `1` 次检索,命中 `['Vue3 入门完全指南', 'Vue3 响应式原理']` 并用 `<mark>` 高亮两处 `Vue3`。

在博客首页落地实时搜索时,将输入框 `v-model="keyword"` 与清空按钮 `✕` 接入组件,并在 `filteredArticles` 计算属性中串联“先按 `activeCategory` 过滤、再对标题与摘要做忽略大小写的 `keyword` 匹配”两步逻辑,使搜索与分类可以叠加生效。本站实测输入 `异步` 命中 `['JS 异步编程详解', 'Vue3 响应式原理']`;再点击 `Vue` 分类收敛为 `['Vue3 响应式原理']`;点击清空按钮后保留 `Vue` 分类并恢复 `['Vue3 入门完全指南', 'Vue3 响应式原理']`;输入无匹配词 `Rust不存在` 显示空态提示 `没有找到匹配的文章`。

watch 支持的三种常见数据源写法

数据源类型标准写法代码示例
单个 ref 响应式引用watch(ref, callback)watch(keyword, fn)
reactive 对象的单个属性(需用 getter 包装)watch(() => obj.prop, callback)watch(() => user.name, fn)
多个响应式源组成的数组watch([ref1, ref2], callback)watch([kw, cat], fn)

watch 与 watchEffect 核心差异对比

特性watchwatchEffect
依赖声明方式需手动显式传入监听源自动收集回调内访问到的所有响应式依赖
初始化执行策略默认懒执行,需配 { immediate: true } 才立即执行注册时立即执行一次以建立初始依赖追踪
新旧值访问能力回调同时接收 (newVal, oldVal)仅能读取当前值,无法直接获取旧值
推荐应用场合需比对前后值、防抖请求或精确限定触发源的副作用不关心旧值、希望自动同步多个关联依赖的副作用

离线 Chromium 实测 watch 三种数据源、watchEffect、防抖合并与博客搜索分类叠加过滤

含完整源码 · 349 行
展开查看收起
python
"""Offline Playwright Chromium lab for Vue 3 Ch 45: watch, watchEffect, debounce & real-time search."""
import json
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")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>BlueSky Blog</title>
<style>
.filter-bar button.active { background: #42b883; color: #fff; }
mark { background: #fff3b0; }
</style>
</head>
<body>
  <section id="search-app">
    <div class="search-bar">
      <input id="search-input" type="text" placeholder="搜索文章标题或摘要...">
      <button id="clear-btn" style="display:none">✕</button>
    </div>
    <div id="category-bar" class="filter-bar"></div>
    <p id="status-tip"></p>
    <div id="article-grid"></div>
  </section>
  <section id="debounce-box">
    <input id="debounce-input" type="text">
    <div id="debounce-result"></div>
  </section>

<script>
// Minimal reactive + watch + watchEffect runtime
let activeEffect = null;
const deps = new WeakMap();

function track(t, k) {
  if (!activeEffect) return;
  let m = deps.get(t);
  if (!m) deps.set(t, (m = new Map()));
  let s = m.get(k);
  if (!s) m.set(k, (s = new Set()));
  s.add(activeEffect);
}
function trigger(t, k) {
  const m = deps.get(t);
  if (!m) return;
  const s = m.get(k);
  if (s) [...s].forEach((fn) => { if (fn !== activeEffect) fn(); });
}
function ref(val) {
  const r = {
    __isRef: true,
    get value() { track(r, 'value'); return val; },
    set value(v) { if (!Object.is(val, v)) { val = v; trigger(r, 'value'); } }
  };
  return r;
}
function reactive(obj) {
  return new Proxy(obj, {
    get(t, k, rec) { track(t, k); return Reflect.get(t, k, rec); },
    set(t, k, v, rec) { const ok = Reflect.set(t, k, v, rec); trigger(t, k); return ok; }
  });
}
function watchEffect(fn) {
  const runner = () => {
    activeEffect = runner;
    try { fn(); } finally { activeEffect = null; }
  };
  runner();
  return runner;
}
function readSource(src) {
  if (Array.isArray(src)) return src.map(readSource);
  if (typeof src === 'function') return src();
  if (src && src.__isRef) return src.value;
  return src;
}
function watch(source, cb, options = {}) {
  let oldVal;
  let initialized = false;
  const runner = () => {
    activeEffect = runner;
    let newVal;
    try { newVal = readSource(source); } finally { activeEffect = null; }
    if (!initialized) {
      initialized = true;
      if (options.immediate) cb(newVal, undefined);
      oldVal = Array.isArray(newVal) ? [...newVal] : newVal;
      return;
    }
    cb(newVal, oldVal);
    oldVal = Array.isArray(newVal) ? [...newVal] : newVal;
  };
  runner();
}

// === Case 1: watch single ref, reactive getter, multi-source, lazy vs immediate ===
const kw1 = ref('');
const cat1 = ref('全部');
const user = reactive({ name: '小明' });
const watchLogs = { single: [], immediate: [], getter: [], multi: [] };

watch(kw1, (n, o) => {
  watchLogs.single.push([o, n]);
  document.title = n ? `搜索:${n}` : 'BlueSky Blog';
});
watch(kw1, (n, o) => {
  watchLogs.immediate.push([o === undefined ? null : o, n]);
}, { immediate: true });
watch(() => user.name, (n, o) => {
  watchLogs.getter.push([o, n]);
});
watch([kw1, cat1], ([nk, nc], [ok, oc]) => {
  watchLogs.multi.push([[ok, oc], [nk, nc]]);
});

const lazyInitialHits = watchLogs.single.length;
const immediateInitialHits = watchLogs.immediate.length;

// === Case 2: watchEffect auto-tracking & immediate execution ===
const effKeyword = ref('');
const miniPosts = ref([
  { id: 1, title: 'Vue3 入门' },
  { id: 2, title: 'JS 异步' }
]);
const effFiltered = ref([]);
const effCounts = [];
watchEffect(() => {
  effFiltered.value = miniPosts.value.filter((a) => a.title.includes(effKeyword.value));
  effCounts.push(effFiltered.value.length);
});

// === Case 3: Debounced watch coalescing rapid inputs + highlight ===
const articles = [
  { id: 1, title: 'Vue3 入门完全指南', summary: '从零开始学习 Vue3 组合式 API', category: 'Vue' },
  { id: 2, title: 'JS 异步编程详解', summary: '搞懂 Promise 和 async/await', category: 'JavaScript' },
  { id: 3, title: 'CSS Grid 布局实战', summary: '用 Grid 实现响应式布局', category: 'CSS' },
  { id: 4, title: 'Vue3 响应式原理', summary: '深入理解 ref 和 reactive 与异步更新', category: 'Vue' }
];
const debKeyword = ref('');
let debTimer = null;
let debRuns = 0;
let debLastMatched = [];

watch(debKeyword, (newVal) => {
  clearTimeout(debTimer);
  debTimer = setTimeout(() => {
    debRuns++;
    const q = newVal.trim().toLowerCase();
    debLastMatched = articles
      .filter((a) => !q || a.title.toLowerCase().includes(q) || a.summary.toLowerCase().includes(q))
      .map((a) => a.title);
    const box = document.getElementById('debounce-result');
    box.innerHTML = debLastMatched
      .map((t) => `<p>${q ? t.replace(new RegExp(newVal.trim(), 'gi'), (m) => `<mark>${m}</mark>`) : t}</p>`)
      .join('');
  }, 180);
});
document.getElementById('debounce-input').addEventListener('input', (e) => {
  debKeyword.value = e.target.value;
});

// === Case 4: Blog real-time search + category combined filter ===
const searchKeyword = ref('');
const activeCategory = ref('全部');
const categories = ['全部', ...new Set(articles.map((a) => a.category))];

function renderBlogSearch() {
  const bar = document.getElementById('category-bar');
  bar.innerHTML = '';
  for (const c of categories) {
    const btn = document.createElement('button');
    btn.textContent = c;
    btn.dataset.cat = c;
    if (activeCategory.value === c) btn.className = 'active';
    btn.addEventListener('click', () => {
      activeCategory.value = c;
      renderBlogSearch();
    });
    bar.appendChild(btn);
  }
  const clearBtn = document.getElementById('clear-btn');
  clearBtn.style.display = searchKeyword.value ? 'inline-block' : 'none';

  let result = articles;
  if (activeCategory.value !== '全部') {
    result = result.filter((a) => a.category === activeCategory.value);
  }
  const kw = searchKeyword.value.trim().toLowerCase();
  if (kw) {
    result = result.filter(
      (a) => a.title.toLowerCase().includes(kw) || a.summary.toLowerCase().includes(kw)
    );
  }
  const tip = document.getElementById('status-tip');
  const grid = document.getElementById('article-grid');
  if (result.length === 0) {
    tip.textContent = '没有找到匹配的文章';
    grid.innerHTML = '';
  } else {
    tip.textContent = `找到 ${result.length} 篇`;
    grid.innerHTML = result.map((a) => `<div class="card"><h3>${a.title}</h3></div>`).join('');
  }
}

document.getElementById('search-input').addEventListener('input', (e) => {
  searchKeyword.value = e.target.value;
  renderBlogSearch();
});
document.getElementById('clear-btn').addEventListener('click', () => {
  searchKeyword.value = '';
  document.getElementById('search-input').value = '';
  renderBlogSearch();
});
renderBlogSearch();

window.__watchLab = {
  runWatchScenarios() {
    kw1.value = 'Vue';
    const titleAfterVue = document.title;
    user.name = '小华';
    cat1.value = 'CSS';
    return {
      lazyInitialHits,
      immediateInitialHits,
      titleAfterVue,
      watchLogs
    };
  },
  runWatchEffectScenario() {
    effKeyword.value = 'Vue3';
    const afterVue = effFiltered.value.map((a) => a.title);
    effKeyword.value = '';
    return { effCounts, afterVue };
  },
  getDebounceReport() {
    return { debRuns, debLastMatched };
  }
};
</script>
</body>
</html>
"""


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            page.set_content(HTML)

            # Case 1: watch single, getter, multi, lazy vs immediate
            w_rep = page.evaluate("window.__watchLab.runWatchScenarios()")

            # Case 2: watchEffect immediate & auto-tracking
            we_rep = page.evaluate("window.__watchLab.runWatchEffectScenario()")

            # Case 3: Debounced watch coalescing 3 rapid inputs into 1 execution + <mark>
            page.evaluate("""() => {
              const inp = document.getElementById('debounce-input');
              for (const v of ['V', 'Vu', 'Vue3']) {
                inp.value = v;
                inp.dispatchEvent(new Event('input', { bubbles: true }));
              }
            }""")
            page.wait_for_timeout(260)
            deb_rep = page.evaluate("window.__watchLab.getDebounceReport()")
            mark_texts = page.eval_on_selector_all("#debounce-result mark", "els => els.map(e => e.textContent)")

            # Case 4: Blog combined search + category filter + clear button + empty state
            page.fill("#search-input", "异步")
            async_titles = page.eval_on_selector_all("#article-grid .card h3", "els => els.map(e => e.textContent)")
            page.click('#category-bar button[data-cat="Vue"]')
            combined_titles = page.eval_on_selector_all("#article-grid .card h3", "els => els.map(e => e.textContent)")
            page.click("#clear-btn")
            after_clear_titles = page.eval_on_selector_all("#article-grid .card h3", "els => els.map(e => e.textContent)")
            page.fill("#search-input", "Rust不存在")
            empty_tip = page.text_content("#status-tip")
        finally:
            browser.close()

    actuals = {
        "watch_single_getter_multi_and_immediate": {
            "lazy_initial_hits": w_rep["lazyInitialHits"],
            "immediate_initial_hits": w_rep["immediateInitialHits"],
            "title_after_vue": w_rep["titleAfterVue"],
            "single_log": w_rep["watchLogs"]["single"],
            "getter_log": w_rep["watchLogs"]["getter"],
            "multi_log": w_rep["watchLogs"]["multi"],
        },
        "watch_effect_immediate_auto_track": {
            "counts": we_rep["effCounts"],
            "after_vue": we_rep["afterVue"],
        },
        "debounced_watch_coalesces_rapid_input": {
            "debounce_runs": deb_rep["debRuns"],
            "matched_titles": deb_rep["debLastMatched"],
            "highlighted_marks": mark_texts,
        },
        "blog_search_and_category_combined_dom": {
            "async_all_categories": async_titles,
            "async_and_vue": combined_titles,
            "after_clear_vue_only": after_clear_titles,
            "empty_tip": empty_tip,
        },
    }
    expected = {
        "watch_single_getter_multi_and_immediate": {
            "lazy_initial_hits": 0,
            "immediate_initial_hits": 1,
            "title_after_vue": "搜索:Vue",
            "single_log": [["", "Vue"]],
            "getter_log": [["小明", "小华"]],
            "multi_log": [[["", "全部"], ["Vue", "全部"]], [["Vue", "全部"], ["Vue", "CSS"]]],
        },
        "watch_effect_immediate_auto_track": {
            "counts": [2, 1, 2],
            "after_vue": ["Vue3 入门"],
        },
        "debounced_watch_coalesces_rapid_input": {
            "debounce_runs": 1,
            "matched_titles": ["Vue3 入门完全指南", "Vue3 响应式原理"],
            "highlighted_marks": ["Vue3", "Vue3"],
        },
        "blog_search_and_category_combined_dom": {
            "async_all_categories": ["JS 异步编程详解", "Vue3 响应式原理"],
            "async_and_vue": ["Vue3 响应式原理"],
            "after_clear_vue_only": ["Vue3 入门完全指南", "Vue3 响应式原理"],
            "empty_tip": "没有找到匹配的文章",
        },
    }
    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()
核对 watch 懒执行与 immediate 差异、getter/多源新旧值记录、watchEffect 立即追踪、3 次连击防抖合并为 1 次并高亮 mark,以及搜索与分类叠加/清空/空结果提示。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a801.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

直接传 user.name 会传入该时刻的普通字符串值而非响应式源,无法建立追踪;用 getter 函数包装后 Vue 才能在求值时收集 user.name 依赖。过滤文章属于纯派生数据,computed 自动追踪多条件并缓存结果,比在 watch 中手动维护一份额外 ref 数组更简洁且不易产生状态不同步。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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