Vue Router 是 Vue.js 官方的路由管理器,用于实现前端应用的路由功能。它提供了声明式和编程式两种方式来处理路由,并支持多种功能和配置选项。本文将介绍 Vue Router 的基础技术点,包括路由的声明式和编程式实现、动态路由配置、命名路由、命名视图、重定向和别名、路由组件传参以及 HTML5 History 模式。
1. 声明式和编程式路由实现方式
Vue Router 提供了两种实现路由的方式:声明式和编程式。
- 声明式:使用
<router-link>
组件进行路由导航,通过to
属性指定目标路由。
<router-link to="/home">Go to Home</router-link>
- 编程式:使用
router.push()
或router.replace()
方法进行路由导航。
// 字符串路径 router.push('home'); // 对象 router.push({ path: 'home' }); // 命名的路由router.push({ name: 'user', params: { userId: 123 }}); // 带查询参数 router.push({ path: 'register', query: { plan: 'private' }});
2. 动态路由配置
Vue Router 支持动态路由配置,可以根据不同的参数值映射到相同的路由。常见的动态路由配置方式包括路径参数和模板参数。
- 路径参数:使用冒号
:
定义不同的路径参数,将不同的参数值映射到相同的路由。
const User = { template: '<div>User {{ $route.params.id }}</div>' }; const router = newVueRouter({ routes: [ { path: '/user/:id', component: User } ] });
- 模板参数:使用
props
配置将参数作为组件的属性传递。
const User = { props: ['id'], template: '<div>User {{ id }}</div>' }; const router = newVueRouter({ routes: [ { path: '/user/:id', component: User, props: true } ] });
3. 嵌套路由和命名视图
Vue Router 支持嵌套路由和命名视图,用于实现复杂的页面布局和多个视图的切换。
- 嵌套路由:在路由配置中使用
children
属性定义子路由,并通过设置相同的路径实现嵌套路由。
const routes = [ { path: '/user/:id', component: User, children: [ { path: 'profile', component: UserProfile } ] } ];
- 命名视图:通过给
<router-view>
组件设置name
属性,实现多个命名视图的渲染。
<router-view></router-view> <!-- 默认视图 --> <router-view name="a"></router-view> <!-- 命名为 "a" 的视图 -->
const routes = [ { path: '/', components: { default: Foo, a: Bar } } ];
4. 响应路由参数的变化
当动态路由参数发生变化时,原来的组件实例会被复用,但是组件的生命周期钩子不会被调用。可以通过监听 $route
对象的变化来响应路由参数的变化。
const User = { template: '...', watch: { '$route'(to, from) { // 响应路由变化 } } };
或者使用 beforeRouteUpdate
守卫来处理路由参数的变化。
const User = { template: '...', beforeRouteUpdate(to, from, next) { // 响应路由变化 // 必须调用 next() 方法 } };
5. 重定向和别名
Vue Router 提供了重定向和别名的功能,用于配置路由的跳转和别名路径。
- 重定向:使用
redirect
属性实现路由的重定向。
const routes = [ { path: '/a', redirect: '/b' }, // 重定向到 /b { path: '/a', redirect: { name: 'foo' }}, // 重定向到命名路由 { path: '/a', redirect: to => { /* 自定义重定向逻辑 */ } } // 动态重定向 ];
- 别名:使用
alias
属性为路由设置别名。
const routes = [ { path: '/a', component: A, alias: '/b' } // /a 的别名是 /b ];
6. 路由组件传参
为了减少组件与路由的耦合性,可以使用 props
将路由参数作为组件的属性传递。
- 对象模式:将
props
设置为true
,将route.params
设置为组件的属性。
const routes = [ { path: '/user/:id', component: User, props: true } ];
- 函数模式:创建一个返回
props
对象的函数,可以对参数进行转换或结合其他值。
const routes = [ { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) } ];
7. HTML5 History 模式
默认情况下,Vue Router 使用 hash 模式来模拟完整的 URL,但可以通过配置 mode: 'history'
使用 HTML5 History 模式。
HTML5 History 模式使用 history.pushState
API 来实现 URL 的跳转,可以隐藏 URL 中的 hash,使 URL 看起来更加美观。使用 HTML5 History 模式需要在服务器端进行相应的配置,确保在直接访问路由时能正确返回对应的页面。
const router = new VueRouter({ mode: 'history', routes: [...] });
配置好服务器后,当用户访问 /user/id
时,服务器应返回同一个 index.html
页面,然后由 Vue Router 来处理对应的路由。这样就实现了在 HTML5 History 模式下的路由切换。
以上就是 Vue Router 的基础技术点,包括路由的声明式和编程式实现、动态路由配置、响应路由参数的变化、重定向和别名、路由组件传参以及 HTML5 History 模式。