如何使用组件从 vuejs 中获取纯数组
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
后安慰.log你的东西,看看你收到了什么。
正如其他答案所指出的,您的getActiveBeers()
调用在执行填充数组的回调之前返回。
你的数组是一个对象的原因是 Vue 在底层数据中包装/扩展数组,以便它可以拦截并响应任何变化的方法——比如推送、弹出、排序等。
您可以在ready
函数的开头记录this.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']
});
相关文章:
- 获取数组的总值
- 按最大值获取数组索引
- React.js如何从js文件中获取数组
- TinyMCE获取数组数据
- 如何获取数组详细信息另一页
- 使用javascript从节点属性获取数组值
- 使用JavaScript获取数组中表单的所有控件
- 获取数组的长度-打印不正确的值
- 正在从JSON对象获取数组
- 什么'获取数组的已定义部分的最快方法是什么?JS
- 如何使用angular指令从html中获取数组
- 如何获取数组中数字的最大出现次数
- 根据优先级获取数组的值
- JAVASCRIPT:获取数组中的值
- 获取数组的元素,无论索引的大小如何
- JavaScript:在XML中搜索节点并从该节点获取数组
- 无法获取数组的长度
- 在数字索引循环中获取数组项的键
- 如何使用JavaScript或jQuery获取数组中选定的optgroup和选项
- Javascript-函数获取数组元素参数未定义/为null