简洁的路由传参详解

95 阅读1分钟

路由传参

传递参数主要有两种类型: params 和 query

query传参

  • 形成的路径:/cart?day=30
  • 路由配置文件中(route.js)的格式:{path: '/cart', component: Cart}
  • 传递的方式:

复制 显示最近30天添加的物品

显示最近30天添加的物品

代码中跳转

//对象的形式并且带参数 this.router.push(/cart?day=30);//等价于this.router.push('/cart?day=30'); // 等价于 this.router.push({path:'/cart?day=30'}); this.$router.push({path: '/cart', query: {day: 30}});

组件内访问:

console.log(this.$route.query.day); // 30

params传参

  • 形成的路径:/cart/30
  • 路由配置文件中(route.js)的格式: { path: "/cart/:day",component: Cart}
  • 传递的方式:

显示最近30天添加的物品

显示最近30天添加的物品

// router.js配置

{ path: "/cart/:day", component: Cart, name: "cart"}

  • 代码中跳转

this.$router.push({path: '/cart', params: { day: 30 }}) ;

  • 组件内访问:

console.log(this.$route.params.day); // 30

访问参数

获取参数是通过 route 对象获取的,路由对象会被注入每个组件中,赋值为 this.route ,并且当路由切换时,路由对象会被更新。

console.log(this.$route)