Vue Router 基础与进阶用法详解
Vue Router 的核心特性
Vue Router 是 Vue.js 官方推荐的路由管理器,具备以下关键功能:
- 支持 HTML5 History 模式和 Hash 模式
- 支持嵌套路由结构
- 支持动态路由参数传递
- 提供编程式导航 API
- 支持命名路由与命名视图
基础路由配置流程
实现一个基本的前端路由系统,需完成以下几个步骤。
1. 使用 router-link 创建导航链接
<router-link> 组件用于生成可点击的导航元素,在页面中会被渲染为 <a> 标签,其 to 属性定义目标路径。
2. 使用 router-view 渲染组件
<router-view> 是路由出口,匹配到的组件将在该位置渲染。
<div class="app">
<router-link to="/profile">个人中心</router-link>
<router-link to="/settings">设置</router-link>
<router-view></router-view>
</div>
3. 定义页面组件
创建需要在路由中加载的 Vue 组件对象。
const Profile = { template: '<h1>个人资料页</h1>' };
const Settings = { template: '<h1>系统设置页</h1>' };
4. 引入 Vue Router 脚本
确保先引入 Vue 再加载 Vue Router,否则会报错。
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
5. 配置路由规则并实例化
通过 VueRouter 构造函数创建路由器实例,并传入路由映射表。
const router = new VueRouter({
routes: [
{ path: '/profile', component: Profile },
{ path: '/settings', component: Settings }
]
});
6. 将路由器挂载到 Vue 实例
将创建好的 router 实例注入根 Vue 实例中。
new Vue({
el: '.app',
router
});
默认重定向配置
初始访问根路径时未显示任何组件?可通过添加重定向规则解决:
const router = new VueRouter({
routes: [
{ path: '/', redirect: '/profile' },
{ path: '/profile', component: Profile },
{ path: '/settings', component: Settings }
]
});
上述配置使应用启动时自动跳转至"个人中心"页面。
嵌套路由实现
当某个页面内部还需进一步划分子页面时,使用嵌套路由。例如,"设置"页面下包含多个子选项。
1. 修改父级组件模板
在父组件中加入子级 router-link 和 router-view。
const Settings = {
template: `
<div>
<h1>系统设置</h1>
<router-link to="/settings/account">账户设置</router-link>
<router-link to="/settings/security">安全中心</router-link>
<router-view></router-view>
</div>
`
};
2. 定义子组件
const Account = { template: '<h2>账户信息管理</h2>' };
const Security = { template: '<h2>密码与验证设置</h2>' };
3. 配置 children 路由
在父路由配置中使用 children 字段定义子路径。
const router = new VueRouter({
routes: [
{ path: '/', redirect: '/profile' },
{ path: '/profile', component: Profile },
{
path: '/settings',
component: Settings,
children: [
{ path: 'account', component: Account },
{ path: 'security', component: Security }
]
}
]
});
注意:子路由路径无需重复前缀,如 account 实际对应完整路径 /settings/account。
命名路由
为路由设置名称后,可在跳转时不依赖具体路径,提高代码可维护性。
{ name: 'profile', path: '/profile', component: Profile }
使用名称进行跳转:
<router-link :to="{ name: 'profile' }">前往个人中心</router-link>
这种方式在路径变更时只需修改路由配置,无需更新所有模板中的硬编码地址。
编程式导航
除了模板中的声明式跳转,还可通过 JavaScript 手动控制路由切换。
const Profile = {
template: `
<div>
<h1>个人中心</h1>
<button @click="jumpToSettings">进入设置</button>
</div>
`,
methods: {
jumpToSettings() {
this.$router.push('/settings');
}
}
};
其他常用方法:
this.$router.go(-1):返回上一页(类似浏览器后退)this.$router.go(1):前进一页this.$router.replace('/login'):替换当前记录,不会留下历史痕迹