asanas
asanas

Reputation: 4280

Vuejs - Update Object in an Array

I am using VueJs and I have an array of objects. What i want to do is update an object in the array based on its index. For that I've written a method:

updateRow(index) {
      this.inputs[index]={ "one": "test", "two": "test" }
    }

However, the object just doesn't update. I've created the following jsbin for it.

https://jsbin.com/boturuluxe/1/edit?html,js,console,output

Any help is appreciated.

Upvotes: 0

Views: 184

Answers (3)

Sajib Khan
Sajib Khan

Reputation: 24204

You can do:

updateRow(index) {
  this.inputs[index]={ "one": "test", "two": "test" };
  this.inputs = Object.assign({}, this.inputs);
  // assigning a new object reference
}

Or,

updateRow(index) {
  this.$set(this.inputs, index, { "one": "test", "two": "test" });
}

Vue docs reference

Upvotes: 0

Roland
Roland

Reputation: 27819

Due to limitations in JavaScript, Vue cannot detect the following changes to an array:

  1. When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue

  2. When you modify the length of the array, e.g. vm.items.length = newLength

The solution is: this.$set(this.inputs, index, { "one": "test", "two": "test" })

Read more here

Upvotes: 2

Asim Khan
Asim Khan

Reputation: 2049

Use this

updateRow(index) {
  Vue.set(this.inputs, index, { "one": "test", "two": "test" })
}

Upvotes: 0

Related Questions