Vue路由傳參的3種形式

Vue路由傳參的3種形式

在列表向詳情頁面跳轉,而後在詳情頁面查看列表的詳情信息,此時設計路由傳參,vue中有3種傳參形式,介紹如下:

<div class="action-btn" @click="viewDetails(item.id)">查看詳情</div>

一、path形式

methods:{
  viewDetails(id) {
       //直接調用$router.push 實現攜帶參數的跳轉
        this.$router.push({
          path: `/particulars/${id}`,
        })
}

此方法,將參數直接拼接在URL上面,需要在路由文件中配置動態路由,具體的配置如下:

{
     path: '/orderDetails/:id',
     name: 'orderDetails',
     component: orderDetails
}

另外,在詳情頁面orderDetails.vue中可以通過 this.$route.params.id 來獲取傳遞的參數,具體如下:

created(){
    this.orderId = this.$route.params.id;
}

優點:頁面刷新不會產生數據丟失的問題。


二、name + params形式

methods:{
  viewDetails(id) {
       this.$router.push({
          name: 'orderDetails',
          params: {
            id: id
          }
        })
  }

此方法,不會將參數直接拼接在URL上面,在路由配置的時候,不需要使用動態路由配置,具體如下:

 {
     path: '/orderDetails',
     name: 'orderDetails',
     component: orderDetails
   }

另外,在詳情頁面orderDetails.vue中可以通過 this.$route.params.id 來獲取傳遞的參數,具體如下:

created(){
    this.orderId = this.$route.params.id;
}

缺點:頁面刷新會產生數據丟失的問題。


三、path + query形式

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

此方法,會將參數拼接到URL上面,並且使用 key=value 的形式,對應的路由不需要配置成動態路由,具體如下:

 {
     path: '/orderDetails',
     name: 'orderDetails',
     component: orderDetails
   }

另外,在詳情頁面 orderDetails.vue 中可以通過 this.$route.query.id 來獲取傳遞的參數,具體如下:

created(){
    this.orderId = this.$route.query.id;
}

四、總結對比

形式 路由 特點 參數獲取 url
name + params 非動態路由 不可刷新 this.$route.params.id /orderDetails
path 動態路由 可刷新 this.$route.params.id /orderDetails/1
path + query 非動態路由 可刷新 this.$route.query.id /orderDetails?id=1

五、溫馨提示

更多博文,請關注:xssy5431 【小拾歲月】

掃碼:
小拾歲月

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章