vue三种传参方式

<p @click="btn(id)"></p>

  

第一种:通过路由中的name属性来确定匹配的路由(实际开发中不推荐)

  子组件通过$route.name接收参数

   {
      path: '/news',
      name: 'News',
      component:News
    }, 

  子组件接收:

<p>{{$route.name}}</p>

  第二种:通过router-link中的to属性

  对应路由配置:

  {
     path: '/describe',
     name: 'Describe',
     component: Describe
   }

  通过路由中的name属性来确定匹配的路由,通过params来传递参数(params是一个对象,里面是key:value的形式):

<router-link :to="{name:'Describe',params:{username:'name',id:'id'}}">goHome</router-link> |

  子组件接收:

this.$route.params.username
this.$route.params.id
或者插值形式直接展示在页面 <p>{{$route.params.username}}-{{$route.params.id}}</p>

  

第二种:通过url传参

  {
     path: '/describe:/newsID(\\d+)/:newsTitle',          这里的正则是为了限制id只能传递数字
     name: 'Describe',
     component: Describe
   }

  路由参数:

<router-link to="/describe/19/hi"></router-link>

  子组件接受参数($route.params):

<p>{{$route.params.newsId}}-{{$route.params.newsTitle}}</p>

第三种:使用path来匹配路由组件,然后通过query来传递参数。这种情况下参数会在url后面显示?id=?

      this.$router.push({
          path: '/describe',
          query: {
            id: id
          }
        })

  对应路由配置:

  {
     path: '/describe',
     name: 'Describe',
     component: Describe
   }

  子组件接收参数:

this.$route.query.id

  

猜你喜欢

转载自www.cnblogs.com/ly-qingqiu/p/11009281.html
今日推荐