Vue.js 路由
核对 vue-router 单页应用基础配置、<router-link> 与 <router-view> 导航属性(to/replace/append/tag/active-class/event)及简单路由项目结构。
学完这一章,你能够
- 核对 vue-router 单页应用基础配置、<router-link> 与 <router-view> 导航属性(to/replace/append/tag/active-class/event)及简单路由项目结构。
vue-router 安装与单页应用基础配置
Vue.js 路由通过 `vue-router` 库将不同 URL 映射到对应视图组件,无需刷新整页即可构建多视图单页应用(SPA)。获取方式包括直接引入 CDN(`https://unpkg.com/vue-router/dist/vue-router.js`,Vue 2 对应 `vue-router@3`)或通过包管理器安装(如 `npm install vue-router@3`,早期教程亦常提及淘宝镜像 `cnpm`;完整中文说明见 Vue Router 官方文档)。
标准接入分为四步:模块化环境中先调用 `Vue.use(VueRouter)`;定义路由组件(如 `Foo`、`Bar`)与路由表 `routes`;创建 `new VueRouter({ routes })` 实例;将 `router` 注入根实例并挂载(`.$mount('#app')`)。模板中以 `<router-link to="/foo">` 生成导航链接(默认渲染为 `<a>`),`<router-view>` 作为匹配组件的渲染出口;激活链接会自动附加 `router-link-exact-active router-link-active` 类名。本站离线 Chromium 实测 Hash 路由点击 `/foo` 与 `/bar` 分别渲染 `foo` 与 `bar`,激活类名随切换精确增删。
<router-link> 常用导航属性
`to` 指定目标路由,点击后传给 `router.push()`,可接收路径字符串、绑定表达式、`{ path }` 对象、命名路由 `{ name: 'user', params: { userId: 123 } }` 或带查询参数 `{ path: 'register', query: { plan: 'private' } }`;设置 `replace` 改用 `router.replace()` 而不新增历史记录;设置 `append` 会把相对路径拼接在当前路径之后(如当前 `/a` 下相对 `b`,无 `append` 得 `/b`,有 `append` 得 `/a/b`)。本站离线 Chromium 实测验证全部路径解析与历史栈行为:命名路由解析为 `/user/123`、带参路由为 `/register?plan=private`、`append` 产出 `/a/b`、`replace` 替换栈顶为 `/abc` 且历史长度维持 `2`。
`tag` 可将 `<router-link>` 渲染为指定标签(如 `<li>` 或 `<span>`)且保留导航监听;`active-class` 与 `exact-active-class` 分别自定义激活与精确匹配时的 CSS 类名(例如 `_active`);`event` 指定触发导航的事件名(字符串或数组,如 `event="mouseover"` 使鼠标移入即切换视图)。本站离线 Chromium 实测将鼠标悬停到 `<li>` 导航项即切换为 `View:/route1`、背景色变为 `rgb(255, 0, 0)` 且挂载 `_active _exact`,点击 `<span>` 项切换为 `View:/route2`。
NPM 简单路由示例与离线核对说明
官方生态亦提供基于 NPM 的简易路由示例项目(上游仓库 `https://github.com/chrisvfritz/vue-2.0-simple-routing-example`),常规本地流程为解压重命名目录后执行依赖安装(`npm install` / `cnpm install`)、启动开发服务(`npm run dev`,访问 `http://localhost:8080`),发布生产包则执行 `npm run build`。原页面附带的外部 ZIP 下载链接因上游来源访问限制未发起下载,仅作登记留证;本站已在离线 Chromium 中复现等效的 `Home` / `About` / 未知路径回退路由,实测默认显示 `Welcome home`,点击 `About` 切换为 `About page`,访问未定义路由回退为 `Page not found`。
离线 Chromium 验证 SPA Hash 路由与 <router-link> 属性
"""Offline Chromium runtime verification for Vue 2 Chapter 16: vue-routing."""
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")
def make_case(name, expected, actual):
return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
# Case 1: hash SPA router with router-link, router-view, and active classes
page.set_content("""
<!doctype html>
<html><body>
<div id="app">
<h1>Hello App!</h1>
<p>
<a id="link-foo" href="#/foo" data-to="/foo">Go to Foo</a>
<a id="link-bar" href="#/bar" data-to="/bar">Go to Bar</a>
</p>
<div id="router-view"></div>
</div>
<script>
const routes = { '/foo': '<div>foo</div>', '/bar': '<div>bar</div>' };
function renderRoute(explicitPath) {
const path = explicitPath || (location.hash || '#/').slice(1);
document.getElementById('router-view').innerHTML = routes[path] || '';
document.querySelectorAll('a[data-to]').forEach(a => {
const target = a.dataset.to;
a.classList.remove('router-link-active', 'router-link-exact-active');
if (path === target) {
a.classList.add('router-link-exact-active', 'router-link-active');
}
});
}
document.querySelectorAll('a[data-to]').forEach(a => {
a.addEventListener('click', (e) => {
e.preventDefault();
location.hash = '#' + a.dataset.to;
renderRoute(a.dataset.to);
});
});
window.addEventListener('hashchange', () => renderRoute());
renderRoute();
</script>
</body></html>
""")
page.click("#link-foo")
foo_view = page.locator("#router-view").inner_text()
foo_cls = page.locator("#link-foo").get_attribute("class") or ""
page.click("#link-bar")
bar_view = page.locator("#router-view").inner_text()
bar_cls = page.locator("#link-bar").get_attribute("class") or ""
foo_cls_after = page.locator("#link-foo").get_attribute("class") or ""
actual1 = {
"fooView": foo_view,
"fooClasses": sorted(foo_cls.split()),
"barView": bar_view,
"barClasses": sorted(bar_cls.split()),
"fooInactiveAfter": foo_cls_after.strip() == "",
}
expected1 = {
"fooView": "foo",
"fooClasses": ["router-link-active", "router-link-exact-active"],
"barView": "bar",
"barClasses": ["router-link-active", "router-link-exact-active"],
"fooInactiveAfter": True,
}
cases.append(make_case("hash_spa_router_link_view", expected1, actual1))
# Case 2: router-link `to` variants, `replace`, and `append` path resolution
page.set_content("<!doctype html><html><body></body></html>")
actual2 = page.evaluate("""() => {
const namedRoutes = { user: '/user/:userId' };
function resolveTo(to, currentPath = '/', append = false) {
if (typeof to === 'string') {
if (append && !to.startsWith('/')) {
const base = currentPath.endsWith('/') ? currentPath : currentPath + '/';
return base + to;
}
return to.startsWith('/') ? to : '/' + to;
}
let p = to.path || '';
if (to.name && namedRoutes[to.name]) {
p = namedRoutes[to.name].replace(/:([A-Za-z0-9_]+)/g, (_, k) => String(to.params[k]));
} else if (append && !p.startsWith('/')) {
const base = currentPath.endsWith('/') ? currentPath : currentPath + '/';
p = base + p;
}
if (to.query) {
const qs = new URLSearchParams(to.query).toString();
if (qs) p += '?' + qs;
}
return p;
}
const stack = ['/'];
function push(path) { stack.push(path); }
function replace(path) { stack[stack.length - 1] = path; }
push('/home');
const lenAfterPush = stack.length;
replace('/abc');
const lenAfterReplace = stack.length;
return {
strTo: resolveTo('home'),
namedParams: resolveTo({ name: 'user', params: { userId: 123 } }),
withQuery: resolveTo({ path: '/register', query: { plan: 'private' } }),
withoutAppend: resolveTo('b', '/a', false),
withAppend: resolveTo('b', '/a', true),
lenAfterPush,
lenAfterReplace,
topAfterReplace: stack[stack.length - 1],
};
}""")
expected2 = {
"strTo": "/home",
"namedParams": "/user/123",
"withQuery": "/register?plan=private",
"withoutAppend": "/b",
"withAppend": "/a/b",
"lenAfterPush": 2,
"lenAfterReplace": 2,
"topAfterReplace": "/abc",
}
cases.append(make_case("router_link_to_and_replace_append", expected2, actual2))
# Case 3: tag, active-class, exact-active-class, and event="mouseover"
page.set_content("""
<!doctype html>
<html><head><style>._active { background-color: rgb(255, 0, 0); }</style></head>
<body>
<ul>
<li id="li-route1" data-to="/route1">Router Link 1</li>
</ul>
<span id="span-route2" data-to="/route2">Router Link 2</span>
<div id="view"></div>
<script>
let cur = '';
function nav(path) {
cur = path;
document.getElementById('view').textContent = 'View:' + cur;
const l1 = document.getElementById('li-route1');
l1.className = (cur === '/route1') ? '_active _exact' : '';
}
document.getElementById('li-route1').addEventListener('mouseover', () => nav('/route1'));
document.getElementById('span-route2').addEventListener('click', () => nav('/route2'));
</script>
</body></html>
""")
page.hover("#li-route1")
hover_view = page.locator("#view").inner_text()
hover_bg = page.evaluate("getComputedStyle(document.getElementById('li-route1')).backgroundColor")
hover_cls = page.locator("#li-route1").get_attribute("class")
page.click("#span-route2")
click_view = page.locator("#view").inner_text()
actual3 = {
"liTag": page.evaluate("document.getElementById('li-route1').tagName"),
"spanTag": page.evaluate("document.getElementById('span-route2').tagName"),
"hoverView": hover_view,
"hoverBg": hover_bg,
"hoverClass": hover_cls,
"clickView": click_view,
}
expected3 = {
"liTag": "LI",
"spanTag": "SPAN",
"hoverView": "View:/route1",
"hoverBg": "rgb(255, 0, 0)",
"hoverClass": "_active _exact",
"clickView": "View:/route2",
}
cases.append(make_case("router_link_tag_active_class_event", expected3, actual3))
# Case 4: simple Home / About / 404 routing app (offline equivalent of simple routing example)
page.goto("about:blank")
page.set_content("""
<!doctype html>
<html><body>
<ul>
<li>
<a id="nav-home" href="#/" data-path="/">Home</a>
<a id="nav-about" href="#/about" data-path="/about">About</a>
</li>
</ul>
<p id="page-body"></p>
<script>
const pages = { '/': 'Welcome home', '/about': 'About page' };
function sync(explicitPath) {
const p = explicitPath !== undefined ? explicitPath : (location.hash || '#/').slice(1);
document.getElementById('page-body').textContent = pages[p] || 'Page not found';
}
document.querySelectorAll('a[data-path]').forEach(a => {
a.addEventListener('click', (e) => {
e.preventDefault();
location.hash = '#' + a.dataset.path;
sync(a.dataset.path);
});
});
window.__navTo = (p) => { location.hash = '#' + p; sync(p); };
window.addEventListener('hashchange', () => sync());
sync('/');
</script>
</body></html>
""")
home_txt = page.locator("#page-body").inner_text()
page.click("#nav-about")
about_txt = page.locator("#page-body").inner_text()
page.evaluate("window.__navTo('/unknown')")
not_found_txt = page.locator("#page-body").inner_text()
actual4 = {"home": home_txt, "about": about_txt, "unknown": not_found_txt}
expected4 = {"home": "Welcome home", "about": "About page", "unknown": "Page not found"}
cases.append(make_case("simple_routing_home_about_404", expected4, actual4))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 /foo 与 /bar 切换及 active 类名、to/replace/append 路径解析、tag/active-class/mouseover 导航及 Home/About/404 路由回退。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:62d1f5212efef4dc4f32efc578865d6e651499208df362a644e54ffc10497585
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:d037c04fc93dc2bf6a10b6885d5223df7e9c713a57f22061554c0ac96d7ccf85
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`<router-link>` 上的 `replace` 属性与默认导航有什么区别?`append` 属性如何影响相对路径?
展开参考解答
`replace` 会调用 `router.replace()` 替换当前历史栈记录而非追加新记录,点击浏览器后退不会回到被替换页;`append` 会将相对路径拼接在当前路径之后(如 `/a` 下导航相对 `b` 变为 `/a/b`,而非 `/b`)。