vue常见的三种传参方式

  • 前言:今天说一下vue常见的三种传参方式,可能网上也有很多资料供大家学习,这里也为了巩固自己再说一下吧

我们先来写三个div,并加上自己的点击事件

<div @click="up('beijing')">点击跳转1 query传参</div>
<div @click="centre('shanghai')">点击跳转2 params传参</div>
<div @click="down('shenzhen')">点击跳转3  直接调用$router.push实现携带参数的跳转</div>

第一种:query传参

    up(x){
      console.log(x)
      this.$router.push({
        path:'/home/detail',
        query:{
          id:x
        }
      });
    }

子组件接收:

{{this.$route.query.id}}

第二种:params传参

    centre(x){
      this.$router.push({
        name:'Detail', //注意这里跟的是组件名
        params:{
          id:x
        }
      });
    },

子组件接收:

{{this.$route.params.id}}

第三种:直接调用$router.push实现携带参数的跳转

   down(id){
      this.$router.push({
        path:`/home/detail/${id}`,  //注意这里用的是模板字符串了而不是引号
      });
    }

需要对应路由配置如下:

{
path: '/home/detail:id',
name: 'Detail',
component: () => import('../components/Detail.vue')
}

*注:这里说下params跟query的区别吧

  • params相当于 post 隐示传输
  • query 相当于get 明文传输
  • $router.push实现携带参数的跳转 path后跟的是模板字符串

猜你喜欢

转载自blog.csdn.net/LingHuzh/article/details/107641158
今日推荐