首页 > 解决方案 > 从 Vue.js 中的内部方法更新数组时不调用 v-for

问题描述

不得不重新提交这个问题,因为有人错误地关闭了它。无论如何,当我更新数组时,我遇到了视图未更新的问题。

我有以下html

<div class="wall" id="wall">
      <div v-for="item in tweet_data" :key="item.id" class="tweet-box">
          // More code here
      </div>
</div>

我的 vue 代码如下所示

var main_twitter_feed = new Vue({
  el: '#wall',
  data: {
    tweet_data: []
  },
  methods: {
    fetch_latest_twitter_feed: function() {
      fetch('/api/fetch-main-twitter-feed').then(function(response) {
        if (response.status !== 200) {
          console.log('Looks like there was a problem. Status Code: ' + response.status);
          return;
        }
        // Examine the text in the response
        response.json().then(function(data) {
          if (data.hasOwnProperty('data')) {
            this.tweet_data = data.data
            console.log(this.tweet_data);
          }
        });
      }).catch(function(err) {
        console.log('Fetch Error :-S', err);
      });
      //    
    }
  }
})

当我调用该方法时,"tweet_data"会更新,但这不会更新v-for视图内部。然而,在我将fetch_latest_twitter_feed()vue 方法移到内部之前,我更像是在外部调用它,就像一个传统的函数

function fetch_latest_twitter_feed() {
  fetch('/api/fetch-main-twitter-feed').then(function(response) {
    if (response.status !== 200) {
      console.log('Looks like there was a problem. Status Code: ' + response.status);
      return;
    }
    // Examine the text in the response
    response.json().then(function(data) {
      console.log(data);
      if (data.hasOwnProperty('data')) {
        main_twitter_feed.tweet_data = data.data
      }
    });
  }).catch(function(err) {
    console.log('Fetch Error :-S', err);
  });
}

并且v-for更新没有问题。有人可以帮忙解释一下区别吗?我不明白为什么在方法部分中移动函数会改变v-for反应的方式。我使用以下方法调用它

window.addEventListener('load', function() {
  main_twitter_feed.fetch_latest_twitter_feed();
  //const interval = setInterval(function() {
  //   fetch_latest_twitter_feed();
  //}, 2000);
})

编辑

我现在已经使用

created() { this.fetch_latest_twitter_feed(); }

并删除了,addEventListener但它仍然没有更新v-for

谢谢

标签: vue.js

解决方案


推荐阅读