vue-router传参数的方式

场景

  我们有两个页面,一个叫做Home,一个叫做About。想要实现从Home点击按钮之后跳转到About页面,并且传递给About页面一个id。

  Home中的点击按钮如下:

<button @click="toAbout(id)">点击我跳转去About页面</button>

一、方式一

  调用this.$router.push实现携带参数的跳转

export default {
  name: 'Home',
  data(){
    return{
      id:123,
    }
  },
  methods:{
    toAbout(id){
      this.$router.push({
        path:`/About/${id}`
      })
    }
  }
}

  在路由的配置中,About页面需要做如下配置:

{
  path: '/about/:id',
  name: 'About',
  component: About
}

  在About页面,通过如下代码获取传递的参数:

this.$route.params

二、方式二

  通过一个名称来标识一个路由显得更方便一些,特别是在链接一个路由,或者是执行一些跳转的时候。通过路由属性中的name来确定跳转的路由,使用params来传递参数。

toAbout(id) {
    this.$router.push({
        name: "About",
        params: {id: id}
    })
}

  About页面的路由配置如下:

{
  path: '/about/:id',
  name: 'About',
  component: About
}

  在About页面,通过如下代码获取传递的参数:

this.$route.params

三、方式三

  可以由path或者name进行跳转,并且通过query来进行参数传递。

  这种情况下,传递的参数会显示在url后通过?id=xxx来显示。

toAbout(id) {
this.$router.push({
name: "About",
// path: "/about",
query: {id: id}
})
}

  About页面的路由配置如下:

{
  path: '/about',
  name: 'About',
  component: About
}

  在About页面,通过如下代码获取传递的参数:

this.$route.query
原文地址:https://www.cnblogs.com/gg-qq/p/13839310.html