- 官方文档:路由对象属性
- 和官方文档的不同点:看文档的过程中一些可能造成歧义的地方(语义层面),进行了扩充
$router.path:当前路由的路径
$route.params:路由参数
- 类型:
object - 一个 key/value 对象,包含了动态片段和全匹配片段,如果没有路由参数,就是一个空对象。
- 动态片段(动态路由参数):在router中用
:声明的片段,是为了把某种模式匹配的所有路由都映射到一个组件。比如下面代码中的:type即为动态路由参数。
{ path: '/Subpage/:type', name: 'Subpage', component: myComponents.Subpage, beforeEnter (to, from, next) { next() }},
- 全匹配片段:vue-router 使用
path-to-regexp 作为路径匹配引擎,所以支持很多高级的匹配模式。例如↓
// a param can be made optional by adding "?" { path: '/optional-params/:foo?' }, // a param can be followed by a regex pattern in parens // this route will only be matched if :id is all numbers { path: '/params-with-regex/:id(\\d+)' }, // asterisk can match anything { path: '/asterisk/*' }, // make part of the path optional by wrapping with parens and add "?" { path: '/optional-group/(foo/)?bar' }
$route.query:查询参数
- 类型:
object - 一个 key/value 对象,表示 URL 查询参数。例如,对于路径 /foo?user=1,则有 $route.query.user == 1,如果没有查询参数,则是个空对象。
- 相当于location.search的key-value版
$route.hash:hash值
- 类型:
string - 当前路由的 hash 值 (带 #) ,如果没有 hash 值,则为空字符串。
- 注意!这里的hash不是路由,例如
http://0.0.0.0:8081/#/Subpage的$route.hash是空字符串而不是#/Subpage。如果想要知道当前路由就必须使用location.hash来获取。 http://0.0.0.0:8081/#/Subpage#title的$route.hash即为#title
$route.fullPath:完整路径
- 类型:
string - 完成解析后的 URL,包含查询参数和 hash 的完整路径。
// url: http://0.0.0.0:8081/?test=true#/Subpage/9kuai9#titleconsole.log(this.$route.fullPath)// '/Subpage/9kuai9#title'console.log(location.hash) // '#/Subpage/9kuai9#title'
- 与$route.path的区别:path不包含哈希
console.log(this.$route.fullPath) // '/Subpage/9kuai9#title'console.log(this.$route.path)// '/Subpage/9kuai9''
$route.matched:当前路由的所有嵌套路径片段的路由记录
- 类型:
Array<RouteRecord> - 一个数组,包含当前路由的所有嵌套路径片段的路由记录 。路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。
const router = new VueRouter({ routes: [ // 下面的对象就是路由记录 { path: '/foo', component: Foo, children: [ // 这也是个路由记录 { path: 'bar', component: Bar } ] } ]})
- 当 URL 为 /foo/bar,$route.matched 将会是一个包含从上到下的所有对象 (副本)。
$route.name:当前路由的名称
- 类型:
string - 当前路由的名称,如果有的话。
- 如果没有,会为
undefined
$route.redirectedFrom:重定向来源的路由
- 类型:
string - 如果存在重定向,即为重定向来源的路由。即使是从
http://0.0.0.0:8081/跳过来的,也会获取到/ - 如果不存在重定向,那么会为
undefined