nogias
nogias

Reputation: 593

Vue JS - Reactivity $set property of property in an object array

My Vue.js version is v1.0.28. I was wondering how I could use Vue.$set to set a deep property of an object array. For example, I have:

this.pairs = [
    {
        "left_media": {
            "name": "A",
            "show": false
        },
        "right_media": {
            "name": "B",
            "show": false
        }
    },
    {
        "left_media": {
            "name": "B",
            "show": false
        },
        "right_media": {
            "name": "A",
            "show": false
        }
    }
]

I need to loop through this.pairs array and update the show property of each media name == A to true.

I can seem to update them easily via a for loop, but the view won't change. I've done some research and seems like Vue.$set can help fix this, but I can't seem to get it work in this case.

How do I use $set to do: this.pairs[i].left_media.show = false;?

EDIT

AJAX call to update show_comment

toggleComment: function(media, which_media) {
  this.$http.post('/api/project-media/update.json', {
    id: media.id,
    show_comment: !media.show_comment
  })
  .then(function (response) {
    if (response.body.success) {
      // update show_comment status for this media in all pairs\
      for (let pair of this.pairs) {
        for (let key of Object.keys(pair)) {
          if (key == 'project_media_left' || key == 'project_media_right') {
            if (pair[key].id == media.id) {
              this.$set(pair[key], 'show_comment', !media.show_comment);
            }
          }
        }
      }
    }
  }, function (response) {
  });
}

Upvotes: 1

Views: 1631

Answers (1)

Bert
Bert

Reputation: 82499

If your target environment supports Object.values or you are using babel or something to compile, then its just

for (let pair of this.pairs)
  for (let v of Object.values(pair))
    if ('A' == v.name) v.show = true

If not then

for (let pair of this.pairs)
  for (let key of Object.keys(pair))
    if (pair[key].name == 'A')
      this.$set(pair[key], 'show', true)

Example.

But to be honest,

for (let pair of this.pairs)
  for (let key of Object.keys(pair))
    if (pair[key].name == prop)
      pair[key].show = true

also works for me, so I wonder if there is something else going on with your issue.

Upvotes: 1

Related Questions