vue-route钩子及query和params传参接参

190 阅读1分钟

一、全局钩子

 在index.js中,你可以使用 router.beforeEach 注册一个全局的 before 钩子:

const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
  // ...
})
复制代码
  • to: 即将要进入的目标
  • from: 当前导航正要离开的路由,没有的话就是null
  • 第三个参数 next是一个必须要调用的函数

   JIRQTT_OAE0OTI$_N2W0JX5.png

router.afterEach(route => { // ...})

二、单个路由独享的钩子

  你可以在路由配置上直接定义 beforeEnter 钩子:

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

  这些钩子与全局 before 钩子的方法参数是一样的

三、query和params

1.query方式传参和接收参数

this.$router.push('目标路径') 还可以实现跳转

传参: 
this.$router.push({
        path:'/xxx',
        query:{
          id:id
        }
      })
  
接收参数:
this.$route.query.id

注意:传参是this.$router,接收参数是this.$route,这里千万要看清了!!!

2.params方式传参和接收参数

传参: 
this.$router.push({
        name:'xxx',
        params:{
          id:id
        }
      })
  
接收参数:
this.$route.params.id

注意:params传参,push里面只能是 name:'xxxx',不能是path:'/xxx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!