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

How can I run functions within a Vue data object?

所以我尝试在 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;
  }
});

以下代码发出如下错误:

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

然而,正如您所看到的,我是 运行 通过我所有的 Contentful entries 的 foreach,然后条目中的每个对象都被推送到一个数组,然后我尝试 return 数组,但出现错误。

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

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

第一件事 - 尽可能保持你的数据模型干净 - 所以那里没有方法。

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

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

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

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

所以将您的逻辑移动到方法中,当您收到数据后,您可以将其分配给 careerData,如下所示:

this.careerData = newData

或像以前一样将内容推送到数组。然后在最后,您可以在一些生命周期挂钩上调用该方法:

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

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

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

  methods: {
    fetchData: function() {
      // your fetch logic here
    }
  }
});

有时您不得不在数据对象中使用函数,例如将数据和函数发布到某些框架组件时(例如 element-ui shortcuts in datepicker)。因为vue中的data其实就是一个函数,可以在里面声明函数在return语句之前:

export default {
data() {
  let onClick = (picker) => {
    picker.$emit('pick', new Date());
    this.myMethod();
  }

  return {
    pickerOptions: {
      shortcuts: [{
        text: 'Today',
        onClick: onClick
      }]}
  };
},
methods:{
  myMethod(){
    console.log("foo")
  }
},
};

如果您愿意,可以用它指向方法。它不是特别干净,但有时会派上用场。