Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  45] [ 6]  / answers: 1 / hits: 48006  / 8 Years ago, fri, january 20, 2017, 12:00:00

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://v2.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


More From » vue.js

 Answers
7

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
}
}
});

[#59270] Wednesday, January 18, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;