geckob
geckob

Reputation: 8120

Watch all properties of a reactive data in Vue.js

I had an API call to the backend and based on the returned data, I set the reactive data dynamically:

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

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

Based on this flow, how can I set watcher for all reactive elements in quantity array dynamically as well?

Upvotes: 1

Views: 827

Answers (2)

Saurabh
Saurabh

Reputation: 73589

You can create a computed property, where you can stringify the quantity array, and then set a watcher on this computed property. Code will look something like following:

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
  }
}

Upvotes: 4

Related Questions