【问题标题】:Vue JS 2 Data Object Changes However Method Doesn't RunVue JS 2 数据对象更改但方法未运行
【发布时间】:2017-01-24 11:41:58
【问题描述】:

我有以下 Vue JS 组件,但在重新渲染数据更改时遇到问题。

Vue.component('careers-list', {
  template: `
  <div id="career-list">
    <div class="context">
      <div v-for="career in careerData">
        <h1>{{ career.fields.jobTitle }}</h1>
        <div v-html="career.fields.jobDescription">
        </div>
      </div>
    </div>
    <div id="career-pagination">
      <button>prev</button>
      <button>1</button>
      <button v-on:click="increaseCount">next</button>
    </div>
  </div>`,

  data: function() {
    return {
     careerData: [],
     paginationCount: 0
    }
  },

  created: function() {
   this.fetchData();
  },

  methods: {
    fetchData: function() {
      client.getEntries({
        skip: this.paginationCount,
        limit: this.paginationCount + 7,
        order: 'sys.createdAt'
      })
      .then(entries => {
        this.careerData = entries.items;
        this.careerData.map(function (career) {
          career.fields.jobDescription = (marked(career.fields.jobDescription));
        });
      });
    },
    increaseCount: function() {
      this.paginationCount += 7;
    }
  }
});

var app = new Vue({
  el: '#app'
});

如您所见,我有一个 fetchData 方法来获取我的数据并对其进行格式化。看看这个方法中的这些行:

skip: this.paginationCount,
limit: this.paginationCount + 7,

在我的应用程序中,这些行决定了将返回多少数据库记录。我在我的数据对象 paginationCount: 0 中使用了这个计数。

然后,我在组件模板中的一个按钮上设置了一个事件:&lt;button v-on:click="increaseCount"&gt;next&lt;/button&gt;

当点击它时,它会使用increaseCount 方法更新paginationCount

当我渲染我的应用程序并单击按钮时,paginationCount 确实会增加,但是我的 fetchData 方法不会重新渲染应用程序以根据计数显示适当的数据。

我认为 Vue 会自动更新其中包含已更改数据对象的任何方法,但我猜事实并非如此,或者我做错了。

知道如何在paginationCount 更改时更新我的​​fetchData 方法吗?

谢谢,尼克

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您需要在此处使用watchers,这完全适合您的用例:

    当您想要执行异步或昂贵的操作以响应不断变化的数据时,这非常有用。

    方法没有被执行,因为你没有从它返回任何东西,这取决于 vue 数据变量。

    paginationCount变量改变时,你必须调用你的方法:

      data: {
         careerData: [],
         paginationCount: 0
      },
      watch: {
        // whenever paginationCount changes, this function will run
        paginationCount: function (newPaginationCount) {
           this.fetchData();
        }
      },
    

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 2021-11-06
      • 2019-12-04
      • 2018-09-20
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      相关资源
      最近更新 更多