Javascript 如何在 Vue 数据对象中运行函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41763723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I run functions within a Vue data object?
提问by Nick Maddren
So I am trying to use the following component within Vue JS:
所以我试图在 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.
但是,正如您所看到的,我正在通过我的所有 Contentful 运行 foreach entries,然后条目中的每个对象都被推送到一个数组,然后我尝试返回该数组,但出现错误。
Any idea how I can extract all of my entriesto my data object within my component?
知道如何entries在组件中提取所有数据对象吗?
When I use the client.getEntries()function outside of my Vue component I get the following data:
当我在client.getEntries()Vue 组件之外使用该函数时,我得到以下数据:
回答by Belmin Bedak
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.
在我写的时候,数据获取和其他逻辑不应该在数据中,在 Vue.js 中有一个保留的对象,称为methods。
So move your logic into the methods, and when you have received the data, you can assign it to careerDatalike this:
所以把你的逻辑移到方法中,当你收到数据时,你可以careerData像这样分配它:
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
}
}
});


