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

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM