vue路由相关

传参

this.$route.push({path:'/xxx',query:{id:1}});//类似get传参,通过URL传递参数 this.$route.push({path:'/xxx',params:{id:1}});//类似post传参


接收参数

 
this.$route.query.id
this.$route.params.id

在路由配置上添加
{ path: '/user/:id', component: User }


路由钩子

全局路由钩子:

 
router.beforeEach((to, from, next) => {
    //会在任意路由跳转前执行,next一定要记着执行,不然路由不能跳转了 console.log('beforeEach') console.log(to,from) // next() }) // router.afterEach((to, from) => { //会在任意路由跳转后执行 console.log('afterEach') })

使用方法:

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: routerConfig
})
 
router.beforeEach((to, from, next) => {
  document.title = to.meta.title || 'demo'
  if (!to.query.url && from.query.url) {
    to.query.url = from.query.url
  }
  next()
})
 
router.afterEach(route => {
})

 

单个路由钩子:
只有beforeEnter,在进入前执行,to参数就是当前路由

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


路由组件钩子:

  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) { // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` }, beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` }

使用方法:
beforeRouteLeave(to, from, next) {
  // ....
  next()
},
beforeRouteEnter(to, from, next) {
  // ....
  next()
},
beforeRouteUpdate(to, from, next) {
  // ....
  next()
},
computed: {},
method: {}

 

 

三种路由钩子中都涉及到了三个参数,这里直接上官方介绍吧

  1. to: Route: 即将要进入的目标 路由对象
  2. from: Route: 当前导航正要离开的路由
  3. next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
  4. next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
  5. next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
  6. next(‘/') 或者 next({ path: ‘/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。
 
 

转载于:https://www.cnblogs.com/Marinnn/p/9481907.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值