2016-12-04 40 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 
    } 
}