在学习本章之前,你需要先查看 “Vue-Router简介和入门” 博文中搭建的 vue-router-simple 项目。本章将依赖该项目进行学习;
我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。例如,我们有一个 User 组件,对于所有 ID 各不相同的用户,都要使用这个组件来渲染。组件的路由地址如下:
# 用户ID为100 /user/100 # 用户ID为200 /user/200 # 在vue-router中我们可以使用 "动态路径参数" (dynamic segment) 的方式来匹配上面两个路由 # 其中:userId将存放我们传递的ID值,如:100,200 /user/:userId
上面两个路由地址均由User组件渲染。实例代码:
User.vue
<template> <div class="user"> <h2>User Page</h2> <!-- 获取我们通过动态路径参数传递过来的用户ID --> <p>id = {{ this.$route.params.id }}</p> </div> </template> <script> export default { name: "User" } </script> <style scoped></style>
index.js
import Vue from 'vue' // 引入路由 import Router from 'vue-router' // 导入自己的组件 import User from '@/components/User' // 使用路由 Vue.use(Router) export default new Router({ routes: [ {path: '/user/:id', name: 'UserLink', component: User} ] })
App.vue
<template> <div id="app"> <img src="./assets/logo.png"> <div class="navigator-container"> <router-link to="/user/100">User-100</router-link> <router-link to="/user/200">User-200</router-link> </div> <div class="content-container"> <router-view/> </div> </div> </template> <script> export default { name: 'App' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 20px; } </style>
运行效果图:
一个“路径参数”使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 this.$route.params,可以在每个组件内使用。见上面的User.vue组件:
<p>id = {{ this.$route.params.id }}</p>
你可以在一个路由中设置多段“路径参数”,对应的值都会设置到 $route.params 中。例如:
// 路由的模式为 /user/:username/post/:post_id // 匹配路径为 /user/evan/post/123 // $route.params为 { username: 'evan', post_id: '123' }
除了 $route.params 外,$route 对象还提供了其它有用的信息,例如,$route.query (如果 URL 中有查询参数)、$route.hash 等等。