2016-12-04 42 views
1

我有一個API調用到後端,並根據返回的數據的反應數據的所有屬性,我動態地設置無功數據:觀看在Vue.js

let data = { 
    quantity: [], 
    tickets: [] 
} 

api.default.fetch() 
    .then(function (tickets) { 
    data.tickets = tickets 
    tickets.forEach(ticket => { 
     data.quantity[ticket.id] = 0 
    }) 
    }) 

在此基礎上的流動,如何能我爲數量數組中的所有無功元素動態設置了監視器?

回答

4

您可以創建一個計算屬性,其中您可以stringify數量數組,然後在此計算屬性上設置一個watcher。代碼看起來像以下:

computed: { 
    quantityString: function() { 
     return JSON.stringify(this.quantity) 
    } 
} 
watch: { 
    // whenever question changes, this function will run 
    quantityString: function (newQuantity) { 
    var newQuantity = JSON.parse(newQuantity) 
    //Your relevant code 
    } 
}