跳至主要內容

vue-router

技术中心大约 4 分钟

vue-router

Vue Router 是 Vue.js 官方的路由管理器。

路由模式

路由组件

用来跳转路由(类似于a标签)

   <router-link to="/">Home</router-link> |
   <router-link to="/about">About</router-link>

router-view

用来显示页面

<router-view/>

路由嵌套

{
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
    children: [{
      path: 'a',
      name: 'AboutA',
      component: {
        render(h) {
          return h('div',{}, '这是aboutA')
        }
      }
    }, {
      path: 'b',
      name: 'AboutB',
      component: {
        render(h) {
          return h('div',{}, '这是aboutB')
        }
      }
    }]
  }

路由跳转

编程式的导航

  • router.push()
  • router.replace()

path跳转

   this.$router.push('/about/a')
   this.$router.push({
     path: '/about/a'
   })

name跳转

 this.$router.push({
   name: 'AboutA'
 })

路由传参

在vue中由一个组件跳转到另一个组件的时候,很多时候需要传递参数,共下一个页面调用 (列表跟详情)

params、query是什么?

  • params:/router1/:id ,/router1/123,/router1/789 ,这里的id叫做params

  • query:/router1?id=123 ,/router1?id=456 ,这里的id叫做query

query方式传递参数

this.$router.push('/about/a?id=111')

this.$router.push({
    path: '/about/a',
    query: {
        id: '111'
    }
})

mounted() {
  this.queryId = this.$route.query.id
  console.log(this.queryId)
}

params方式传递参数

{
  path: 'b/:id',
  name: 'AboutBParams',
  component: () => import('../views/AboutBParams.vue'),
}

this.$router.push('/about/b/222')
this.$router.push({
  name: 'AboutBParams',
  params: {
    id: 333
  }
})

不声明路径直接传递params

 this.$router.push({
  name: 'AboutB',
  params: {
    id: 333
  }
})

缺点: 当页面刷新的时候数据会丢失

路由守卫

vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。

有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。

全局守卫

全局前置守卫:

可以使用 router.beforeEach 注册一个全局前置守卫:

router.beforeEach((to, from, next) => {
  next()
})
  • to: Route: 即将要进入的目标 路由对象

  • from: Route: 当前导航正要离开的路由

  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

    • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

    • next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

    • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。

    • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

全局后置钩子:

也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:

router.afterEach((to, from) => {
  // ...
})

路由独享的守卫

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
        }
    }
  ]
})

组件内的守卫

  • beforeRouteEnter

    • 在渲染该组件的对应路由被 confirm 前调用

    • 不!能!获取组件实例 this

    • 因为当守卫执行前,组件实例还没被创建

    beforeRouteEnter (to, from, next) {
        next(vm => {
          // 通过 `vm` 访问组件实例
          // 在渲染该组件的对应路由被 confirm 前调用
          // 不!能!获取组件实例 `this`
          // 因为当守卫执行前,组件实例还没被创建
          console.log("beforeRouteEnter")
        })
      },
    
  • beforeRouteUpdate (2.2 新增)

    • 在当前路由改变,但是该组件被复用时调用

    • 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,

    • 由于会渲染同样的 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。

    • 可以访问组件实例 this

    beforeRouteUpdate (to, from, next) {
      // 在当前路由改变,但是该组件被复用时调用
      // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
      // 由于会渲染同样的 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
      // 可以访问组件实例 `this`
      console.log(beforeRouteUpdate)
      next()
    }
    
  • beforeRouteLeave

    • 导航离开该组件的对应路由时调用
    • 可以访问组件实例 this
    beforeRouteLeave (to, from, next) {
      // 导航离开该组件的对应路由时调用
      // 可以访问组件实例 `this`
      const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
      if (answer) {
        next()
      } else {
        next(false)
      }
    }