Vue.js与Vuetify:如何将LocalBase查询结果存入orgs数组
问题原因与解决方案
错误原因
- 初始状态下
this.orgs是空数组,调用this.orgs.forEach(...)时循环不会执行任何回调逻辑,自然没有数据被添加到数组中。 - 循环参数命名为
response,和外层的查询结果变量重名,会导致变量覆盖,即使循环执行也会出现逻辑错误。
修复代码
推荐使用map方法直接将查询结果映射为需要的结构,赋值给this.orgs,代码更简洁高效:
this.$db.collection('orgs').get({ keys: true }) .then(response => { console.log('orgs: ', response); this.orgs = response.map(item => ({ person: item.data.person, orgName: item.data.orgName, due: item.data.due, id: item.key })); });
如果需要保留原数组的已有数据(不替换而是追加),可以遍历查询结果再push:
this.$db.collection('orgs').get({ keys: true }) .then(response => { console.log('orgs: ', response); // 遍历查询返回的response数组,而非空的this.orgs response.forEach(item => { const data = { person: item.data.person, orgName: item.data.orgName, due: item.data.due, id: item.key }; this.orgs.push(data); }); });
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

