$router 和 $route

4,563 阅读1分钟

1, router 和route 的区别

  • router为 VueRouter 实例,是路由操作对象,只写对象,想要导航到不同url,则使用router.push方法

  • $route为当前router跳转对象,路由信息对象,只读对象,里面可以获取name、path、query、params等

    // this.$router.push()
    // this.$router.replace()
    // this.$router.go()

2, this.route.params和this.route.query

1, params方式传参和接收参数

// 传参: 
this.$router.push({
    name: 'index'
    params:{
      id:id
    }
  })
  
// 接收参数:
this.$route.params.id
 
// url的表现形式(url中没有参数)
http://localhost:8080/#/index

// 路由
{
   path: '/index/:id/:name',
   name: 'index',
   component: index // 这个index是传进来的组件名称
 }

2, query方式传参和接收参数

// 传参
this.$router.push({
    path: '/index'
    query:{
      id:id
    }
 })

//接收参数
this.$route.query.id

// url的表现形式(url中带有参数)
http://localhost:8080/#/index?id=1
  • 1,params传参,push里面只能是 name:'xx',不能是path:'xx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined

  • 直白的来说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,而params相当于post请求,参数不会再地址栏中显

  • params是路由的一部分,必须要有 , query是拼接在url后面的参数,没有也没关系

  • query刷新 不会 丢失query里面的数据, params刷新 会 丢失 params里面的数据

  • 传参是this.router,接收参数是this.route