区分$router和$route
this.$router:router 实例
const router = new VueRouter({})
this.$route:当前激活的路由信息对象
watch: {
// 监听路由变化
$route (to, from) {
if (to.matched[0].path !== from.matched[0].path) {
xxxxxx
}
}
}
路由对象this.$route
一个路由对象 (route object) 表示当前激活的路由的状态信息,包含了当前 URL 解析得到的信息,还有 URL 匹配到的路由记录 (route records)。
路由对象是不可变 (immutable) 的,每次成功的导航后都会产生一个新的对象。
路由对象出现在多个地方:
- 在组件内,即 this.$route($route是路由对象)
- 在 $route 观察者回调内
- router.match(location) 的返回值
- 导航守卫的参数:( `to` 和 `from` 都是路由对象)
router.beforeEach((to, from, next) => {
// `to` 和 `from` 都是路由对象
})
- scrollBehavior 方法的参数:
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
// `to` 和 `from` 都是路由对象
}
})
路由对象属性
$route.path:对应当前路由的路径,总是解析为绝对路径,如 "/foo/bar"
$route.fullPath:完成解析后的 URL,包含查询参数和 hash 的完整路径。
$route.matched:一个数组,包含当前路由的所有嵌套路径片段的路由记录 。路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。
示例1:
当前url:http://localhost:2020/cm/bst/list/list
router对象中的路由记录为:
const router = new VueRouter({
mode: 'history',
routes: [
// 下面的对象就是路由记录
{
path: '/cm',
name: 'cm',
component: Main,
children: [
{
// 这也是个路由记录
path: 'bst',
name: 'businessTerminal',
component: Layout,
children: [
{
// 这也是个路由记录
path: 'list',
name: 'cmList',
component: Layout,
children: [
{
// 这也是个路由记录
path: 'list',
name: 'cmList',
component: () => import(/* webpackChunkName: "equipment" */ '@/views/bs/equipment')
}
]
}
}
]
})
this.$route.matched匹配到的路由记录为:
- /cm
- /cm/bst
- /cm/bst/list
- /cm/bst/list/list
<router-view>组件与this.$route.matched
<router-view> 组件是一个 functional 组件,渲染路径匹配到的视图组件,路径匹配到的组件就是this.$route.matched匹配到的路由记录的视图组件。
router实例this.$router
this.$router.options就是new Router({})传进去的参数
使用方法:
const router = new VueRouter({options})
示例2:
const router = new VueRouter({ mode: 'history', routes: [...] })
打印this.$route.options,得到的就是:
{ mode: 'history', routes: [...] }
上面示例1打印的this.$route.options得到: