命名路由是提升路由跳转安全性与可维护性的核心实践,通过唯一字符串name替代硬编码路径,支持声明式与编程式跳转、动态参数传递、路由守卫精准判断及调试优化。
命名路由不是锦上添花的功能,而是让路由跳转更安全、更易维护的核心实践。它用一个名字代替硬编码的路径字符串,避免拼写错误、路径变更时四处修改的问题。
每个路由对象都可以添加 name 属性,值为字符串,全局唯一即可:
// router/index.js
const routes = [
{ path: '/home', name: 'home', component: Home },
{ path: '/user/:id', name: 'user-detail', component: UserDetail },
{ path: '/product/:sku', name: 'product-page', component: ProductPage }
];
user-detail 比 user 更明确:id)同样支持命名,后续传参方式会更统一*)设 name,它们通常不参与主动跳转替换原来的字符串 to="/user/123",改用对象语法:
<router-link :to="{ name: 'user-detail', params: { id: 123 } }">用户页</router-link>
<router-link :to="{ name: 'product-page', params: { sku: 'PRO-001' } }">商品详情</router-link>
:id),不能写成 query{ name: 'home' }
active-class 或 exact-active-class 仍可正常使用在 methods 或组合式 API 的 setup 中,推荐这样写:
// Vue 2 写法
this.$router.push({ name: 'user-detail', params: { id: this.userId } });
// Vue 3 + Composition API
import { useRouter } from 'vue-router';
const router = useRouter();
router.push({ name: 'product-page', params: { sku: skuValue } });
$router.push('/user/' + id),这里不会因路径格式变化(如改成 /u/:id)而报错{ name: 'user-detail', params: { id: 5 }, query: { tab: 'posts' } }
在 beforeEach 等导航守卫中,to.name 比 to.path 更稳定可靠:
router.beforeEach((to, from, next) => {
if (to.name === 'user-detail' && !isLogin()) {
next({ name: 'login', query: { redirect: to.fullPath } });
} else {
next();
}
});
router.push({ name: 'home' }) 无需构造路径