[Vuejs]-Vue: Accessing elements of a bound variable containing an array

0👍

Directly assigning to a particular index in an array is not reactive: List rendering caveats:

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

Instead, try this.form_in_progress.splice(key, 1, value);.


Consider the following example:

changeWithBrackets will do what your code does effectively:

this.form_in_progress[key] = value;

changeWithSplice will do what I propose:

this.form_in_progress.splice(key, 1, value);

Demo:

const app = new Vue({
  el: "#app",
  data() {
    return {
      items: ["foo", "bar", "fizz", "buzz"]
    };
  },
  methods: {
    changeWithBrackets() {
      this.items[0] = "world";
    },
    changeWithSplice() {
      this.items.splice(0, 1, "world");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="item in items">{{item}}</li>
  </ul>
  <button @click="changeWithBrackets">Change with brackets</button>
  <button @click="changeWithSplice">Change with splice</button>
</div>

Leave a comment