0

I've bound the input in this tiny app to a computed property called currentCat which has both a getter and setter method. Using console.log it can been seen that the cats array has been property updated, but none of the changes are reflected in the rendered html.

Here is the HTML for the app:

<div id="app">
  <ul>
    <li v-for="cat in cats">{{ cat }}</li>
  </ul>
  <div>{{ currentCat }}</div>
  <input type="text" v-model="currentCat">
</div>

And here is the JavaScript:

let app = new Vue({
  el: "#app",
  data: {
    currentCatIndex: 0,
    cats: ["Bob", "Tom", "Cat", "Dog"]
  },
  computed: {
    currentCat: {
      get() {
        return this.cats[this.currentCatIndex];
      },
      set(value) {
        console.log(value, this.cats[this.currentCatIndex]);
        this.cats[this.currentCatIndex] = value;
        console.log(this.cats[this.currentCatIndex]);
      }
    }
  }
});

Shouldn't the list and the div in the html update automatically when the computed property's setter runs?

1 Answer 1

2

Vue can't detect changes to an array when you do:

this.cats[this.currentCatIndex] = value;

Use one of the followings instead:

this.$set(this.cats, this.currentCatIndex, value)

// or
this.cats.splice(this.currentCatIndex, 1, value)

See list rendering caveats.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.