Vue.js v-for not rendering component

Viewed 633

I have the following issue, for some reason, the v-for will not render at all. Please find the fiddle here https://jsfiddle.net/tadeyemi/k6s4gv85/ I have absolutely no idea why it isn't working. Someone care to shed some light?

<div id="app">
  <h1>Finds</h1>
  <div>
    <input ref="option">
  </div>
  <button v-if @click="addFind">
    New Find
  </button> 
  <p v-for="(option,idx) in options.slice(1)">
    <span @click="removeOption(idx+1)">Option{{idx+1}}: {{option}}</span>
  </p>
</div>

and the JavaScript as follows:

new Vue({
  el: '#app',
  data: {
    options: [],
    count:0
  },
  methods: {
    addFind: function () {
    var msg = this.$refs.option.value;
    console.log(this.options);
    if( msg.trim() != "" ){
        this.count++;
        var i = this.count;
      this.options[i]= this.$refs.option.value.trim();
    }
    },
    removeOption:function(index){

    this.options.splice(index,1);
    this.count--;

    }
  }
});
1 Answers

There are some issues with your code, but the most prominent is that you break some reactivity rules explained here: https://v2.vuejs.org/v2/guide/reactivity.html#For-Arrays

Vue cannot detect the following changes to an array:

When you directly set an item with the index, e.g. vm.items[indexOfItem] = newValue When you modify the length of the array, e.g. vm.items.length = newLength

Basically: this.options.push(msg.trim()); would work, while this.options[i]= this.$refs.option.value.trim(); won't

I edited the fiddle a little to make it work: https://jsfiddle.net/63jyw7gz/

Related