我正在使用对数据库的调用来检索一些结果并将其推入数组。但是,当我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']
});
另一个答案是正确的,getActiveBeers
发送HTTP请求,然后立即返回数组,它不等待ajax请求返回。您需要处理activeBeers
ajax请求的成功功能中的更新。您可以使用该.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']
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句