$router和$route

区分$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匹配到的路由记录为:

  1. /cm
  2. /cm/bst
  3. /cm/bst/list
  4. /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得到:

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值