How can I run functions in a Vue data object?

Therefore, I am trying to use the following component in 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 this error:

 [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 run foreach through my entire Contentful entries , then each object inside the records is placed in an array, and then I try to return the array, but I get an error.

Any idea how I can extract all my entries into my data object in my component?

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

enter image description here

+5
source share
1 answer

This path is absolutely wrong.

First of all, keep the data model as clean as possible, so there are no methods.

Secondly, as the error says, when you are dealing with data in a component, the data should be functions that return an object:

 Vue.component('careers', { template: '<div>A custom component!</div>', data: function() { return { careerData: [] } } }); 

As I write, data sampling and other logic should not be in the model, so for VueJS there is an object reserved for VueJS called methods

So, move your logic to a method, and when you have the data, you can assign it to a career by assigning it like this:

 this.careerData = newData 

or drag objects into an array, as 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 } } }); 
+8
source

Source: https://habr.com/ru/post/1263095/


All Articles