2017-09-26 64 views
0

新來Vuejs的,有關於更新陣列的問題。添加項目來結束陣列動態

這是我的數據(status_arr):

{ 
    "Approvals": [ 
     { 
      "name": "Section 1", 
      "count": 10692 
     } 
    ], 
    "Declines": [ 
     { 
      "name": "Section 1", 
      "count": 1212 
     }, 
     { 
      "name": "Section 2", 
      "count": 5 
     } 
    ] 
} 

我需要動態地添加上述數據的"Pending"一部分。我不是很瞭解如何做到這一點的方法$set。我需要添加到上面的數據集中,而不影響其中的其餘數據。

文檔說使用:

this.$set(status_arr, itemIndex, [ { 'name': 'Section 1', 'count': 0 } ]); 

不知道如何添加Pending部分附帶的數據,如果我加入到陣列中,它是如何有一個itemIndex我這樣做?是否有一個this.$add功能或東西就像一個pop()

感謝您的幫助!

+0

在添加* Pending *部分後,'status_arr'對象應該是什麼樣子? – Phil

回答

2

如果我正確理解你的問題,你想

this.$set(this.status_arr, 'Pending', [{ 
    name: 'Section 1', 
    count: 0 
}]) 
+0

這正是我想要的。謝謝! – Sean

+0

@謝恩,不客氣。看到這是不太可能,如果您嘗試訪問'status_arr觸發錯誤備選方案,[其他答案](https://stackoverflow.com/a/46416156/283366)。*之前* *已填充它 – Phil

1

您可以更改status_array這樣:

{ 
    "Approvals": [ 
     { 
      "name": "Section 1", 
      "count": 10692 
     } 
    ], 
    "Declines": [ 
     { 
      "name": "Section 1", 
      "count": 1212 
     }, 
     { 
      "name": "Section 2", 
      "count": 5 
     } 
    ], 
    "Pending": [] 
} 

而當你想要更多的項目加入到之前,你可以使用:

status_array.Pending.push(newEle) 

請記住,Vue包裝了觀察數組的突變方法他們也會觸發視圖更新。被包裝的方法有:

  • 推()
  • 彈出()
  • 移()
  • 不印字()
  • 剪接()
  • 排序()
  • 反向()
0

Vue的不動態允許增加新的根級別的反應性屬性到已經創建的實例。但是,可以使用Vue.set或this。$ set將反應性屬性添加到嵌套對象。這是我如何實現它:
一個構造函數返回希望的對象

addObj(name, count) { 
    return { 
     name: name, 
     count: count 
    } 
} 

調用此函數

var newObj = new this.addObj('tom', 6); 
this.$set(this.status_arr, 'Pending', newObj); 

如果你想刪除一個關鍵值對:

this.$delete(this.status_arr, 'Pending');