如何在Vue数据对象中运行函数?

Nic*_*ren 10 javascript vue.js vue-component

所以我试图在Vue JS中使用以下组件:

Vue.component('careers', {
  template: '<div>A custom component!</div>',

  data: function() {

    var careerData = [];

    client.getEntries()
    .then(function (entries) {
      // log the title for all the entries that have it
      entries.items.forEach(function (entry) {
        if(entry.fields.jobTitle) {
          careerData.push(entry);
        }
      })
    });

    return careerData;
  }
});
Run Code Online (Sandbox Code Playgroud)

以下代码发出如下错误:

[Vue warn]: data functions should return an object:
https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function 
(found in component <careers>)
Run Code Online (Sandbox Code Playgroud)

但是你可以看到我正在通过我的所有Contentful运行foreach entries,然后条目中的每个对象被推送到一个数组,然后我尝试返回数组但是我得到一个错误.

知道如何entries在组件中提取我的所有数据对象吗?

当我在client.getEntries()Vue组件之外使用该函数时,我得到以下数据:

在此输入图像描述

Bel*_*dak 19

这种方式完全错了.

首先要做的是 - 尽可能保持数据模型的清洁 - 所以没有方法.

第二件事,正如错误所说,当你将数据处理成组件时,数据应该是返回对象的函数:

Vue.component('careers', {
  template: '<div>A custom component!</div>',

  data: function() {
    return {
     careerData: []
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

在我写的时候,数据提取和其他逻辑不应该在数据中,在Vue.js中有一个为其保留的对象methods.

因此,将您的逻辑移动到方法中,当您收到数据时,可以将其分配为careerData:

this.careerData = newData
Run Code Online (Sandbox Code Playgroud)

或者像以前一样将数据推送到数组中.然后在最后,您可以在某些生命周期钩子上调用该方法:

Vue.component('careers', {
  template: '<div>A custom component!</div>',

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

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

  methods: {
    fetchData: function() {
      // your fetch logic here
    }
  }
});
Run Code Online (Sandbox Code Playgroud)