0

i'm getting a strange issue where when I change my data within my Vue instance, the HTML is not updating:

CodePen

HTML:

<div class="favourites-panel__wrapper" id="app">
  <ul>
    <li v-for="(vehicle, index) in vehicles">{{ vehicle.id }}</li>
  </ul>
  <a href="javascript:void(0);" v-on:click="add()">Add</a>
</div>

JavaScript:

window.panel = new Vue({
    el: '#app',
    data: {
        vehicles: {}
    },
    created: function() {

        // Create dummy vehicles
        for (var i = 0; i < 4; i++) {
            this.vehicles[i] = this.dummy(i);
        }

    },
    methods: {
      add: function() {
        let index = Object.keys(this.vehicles).length;
        let dummy = this.dummy(index);

        this.vehicles[Object.keys(this.vehicles).length] = dummy;
      },
      dummy: function(i) {
        return {
          'dummy': true,
          'body': 'loading',
          'fuel_type': 'loading',
          'gearbox_type': 'loading',
          'id': 'loading' + i,
          'image': '/assets/images/themev2/compare-dummy.gif',
          'image_id': 'loading',
          'make': 'loading',
          'model': 'loading',
          'location_name': 'loading',
          'variant': 'loading',
          'web_price': 'loading'
        }
      }
    }
});

1 Answer 1

1

use

Vue.set(this.vehicles, Object.keys(this.vehicles).length, dummy);

insted of

this.vehicles[Object.keys(this.vehicles).length] = dummy;
Sign up to request clarification or add additional context in comments.

3 Comments

This seems to work, how come I need to use Vue.set, where in the documentation example I can just add an object as normal? Is it because my vehicles data is an object rather than a key? vuejs.org/v2/guide/list.html
Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method: from official documentaion. vuejs.org/v2/guide/reactivity.html
Caveats:: Due to limitations in JavaScript, 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

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.