How can I run functions within a Vue data object?

老子叫甜甜 提交于 2019-12-08 15:44:47

问题


So I am trying to use the following component within 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;
  }
});

The following code emits an error like so:

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

However as you can see I am running a foreach through all of my Contentful entries, then each object within entries is being pushed to an array, I then try to return the array but I get an error.

Any idea how I can extract all of my entries to my data object within my component?

When I use the client.getEntries() function outside of my Vue component I get the following data:


回答1:


This way is totally wrong.

First thing first - keep your data model as clean as possible - so no methods there.

Second thing, as error says, when you are dealing with data into component, data should be function that returns an object:

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

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

As I write, data fetching and other logic shouldn't be in the data, there is an object reserved for that in Vue.js called methods.

So move your logic into the methods, and when you have received the data, you can assign it to careerData like this:

this.careerData = newData

or push things to the array like you did before. And then at the end, you can call the method on some lifecycle hooks:

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

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

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

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


来源:https://stackoverflow.com/questions/41763723/how-can-i-run-functions-within-a-vue-data-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!