【问题标题】:v-for object in objects doesn't rerender when this.objects changes当 this.objects 更改时,对象中的 v-for 对象不会重新呈现
【发布时间】:2019-10-16 12:30:14
【问题描述】:

我有一个mounted()reloadComparisons() 和这个标签:

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

问题是只有在data中定义了comparisons时才会渲染,当我加载新数组时,它不起作用。

我已经尝试过Vue.set(this.comparisons,comparisons),但它也没有反应。

你知道该怎么做吗?

编辑

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()
                }
            }
        });

【问题讨论】:

  • 你能提供使用代码吗?
  • @Ifaruki 是的,我已经添加了代码

标签: javascript vue.js v-for


【解决方案1】:

我认为您丢失了 this 上下文。请尝试以下操作:

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()
   }

甚至更好:如果您使用 webpack(或其他带有 babel 的现代构建链),请使用箭头函数,以便您的上下文保持正确

【讨论】:

  • 是的,是问题所在,我用其他方法解决了,我只是使用app.comparisons = 而不是this.comparisons = ,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 2016-08-24
  • 2021-07-15
  • 1970-01-01
  • 2019-09-22
相关资源
最近更新 更多