[英]How do I get a plain array back from vuejs with a component?
我正在使用对数据库的调用来检索一些结果并将其推入数组。 但是,当我console.log(this.activeBeers)
我没有得到数组,而是得到了一个对象。 如何获得普通数组而不是对象?
Vue.component('beers', {
template: '#beers-template',
data: function() {
return {
activeBeers: []
}
},
ready: function() {
function getActiveBeers(array, ajax) {
ajax.get('/getbeers/' + $('input#bar-id').val()).then(function (response) {
$.each(response.data, function(key, value) {
array.push(value.id);
});
}, function (response) {
console.log('error getting beers from the pivot table');
});
return array;
}
console.log(this.activeBeers = getActiveBeers(this.activeBeers, this.$http));
},
props: ['beers']
});
AJAX是异步完成的,因此您将无法仅返回尚未拥有的值。
您应该在$.each
之后用console.log记录您的内容,以查看收到的内容。
正如其他答案所指出的那样,在填充数组的回调执行之前, getActiveBeers()
调用将返回。
您的数组是对象的原因是因为Vue在基础数据中包装/扩展了数组,以便Vue可以拦截和响应任何变异方法,例如push,pop,sort等。
您可以在ready
函数的开始处记录this.activeBeers
,以查看它是一个对象。
顺便说一句,如果要记录activeBeers
的展开/纯数组, activeBeers
可以使用组件的$log
方法:
this.$log(this.activeBeers);
另一个答案是正确的, getActiveBeers
发送一个HTTP请求,然后立即返回该数组,它不等待ajax请求返回。 您需要在ajax请求的成功函数中处理activeBeers
的更新。 您可以使用.bind()
函数,以确保this
在你的成功的功能是指Vue
组件,这样你可以直接按ID添加到您的activeBeers
阵列。
Vue.component('beers', {
template: '#beers-template',
data: function() {
return {
activeBeers: []
}
},
ready: function() {
this.getActiveBeers();
},
methods: {
getActiveBeers: function(){
this.$http.get('/getbeers/' + $('input#bar-id').val()).then(function (response) {
$.each(response.data, function(key, value) {
this.activeBeers.push(value.id);
}.bind(this));
console.log(this.activeBeers);
}.bind(this), function (response) {
console.log('error getting beers from the pivot table');
});
}
}
props: ['beers']
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.