Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run functions within a Vue data object?

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:

enter image description here

like image 612
Nick Maddren Avatar asked Jan 20 '17 12:01

Nick Maddren


1 Answers

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
    }
  }
});
like image 66
Belmin Bedak Avatar answered Oct 26 '22 20:10

Belmin Bedak