Search code examples
javascriptvue.jsv-for

v-for object in objects doesn't rerender when this.objects changes


I have a mounted() with reloadComparisons() and this tag:

<li v-for="comparison in comparisons">C: [[ comparison.area ]]</li>

The problem is that this is rendered only when comparisons is defined in data, when I load new array, it doesn't work.

I tried already Vue.set(this.comparisons,comparisons) but it doesn't react neither.

Do you know what to do?

EDIT

var app = new Vue({
            delimiters: ['[[', ']]'],
            el: '#vue',
            data: {
                comparisons: [{'area': 'xxxx'}],
            },
            mounted() {
                this.reloadComparisons()
            },
            methods: {
                reloadComparisons: function () {
                    console.log('reloadComparisons');
                    axios.get("http://127.0.0.1:8000/alex/api/pricemap_comparisons/").then(function (response) {
                        console.log(response);
                        if (response.status === 200) {
                            this.comparisons = response.data.results;
                            Vue.set(this.comparisons, response.data.results);
                            console.log(this.comparisons);
                        }
                    }).catch()
                }
            }
        });

Solution

  • I think you lost your this context. Try the following:

    reloadComparisons: function () {
        console.log('reloadComparisons');
        const that = this;                   
      axios.get("http://127.0.0.1:8000/alex/api/pricemap_comparisons/")
        .then(function (response) {
            console.log(response);
            if (response.status === 200) {
               that.comparisons = response.data.results;
               Vue.set(that.comparisons, response.data.results);
               console.log(that.comparisons);
            }
         )}.catch()
       }
    

    Or even better: If you use webpack (or other modern buildchains with babel) use arrow functions so your context keeps right