Vue.js:如何使用v-for迭代到动态数组中



我想显示多个工具的html表(1个表=1个工具的类别/1个tr=1个工具(。

data() {
return {
cats: '',
tools: [],
};
},
methods: {
getToolCats() {
var rez = getToolCats();
rez.then(data => this.receiveCats(data) ) 
},
receiveCats(_cats){
this.cats = _cats;
_cats.forEach(cat => {
getToolsByCat(cat.href).then(data => this.tools[cat.href] = data);
});
console.log(this.tools);
},
},
mounted() {
this.getToolCats();
},

cats(即类别(是一个用API调用填充的数组。然后,对于每一个cat,API调用会给我一个该cat的工具列表,我将其放入tools数组(this.tools[cathref]=data(。

这是显示代码:

<div v-for="cat in cats" :key="cat.href" class="tbox col-xs-12 col-sm-6">
....
<table class="table table-hover">
<tr v-for="tool in tools[cat.href]" :key="tool.href">
<td>...</td>
</tr>
</table>
....
</div>

如果我用一个var来存储工具列表,一切都可以。但是,虽然我不知道我会有多少只猫,但我不能为每个类别创建一辆车。

我认为问题可能就在那里:

  • 在v-for中使用一个数组,该数组的键未在挂载状态下定义:

v-for="工具中的工具[cat.href]

如有任何帮助,我将不胜感激!

Vue无法检测到this.tools[cat.href] = data中的动态属性添加,但它可以检测到this.$set(this.tools, cat.href, data)this.$setVue.set的变化:

new Vue({
el: '#app',
data() {
return {
cats: [],
tools: {}, // <-- make this an object (not an array)
};
},
mounted() {
this.getToolCats();
},
methods: {
getToolCats() {
// setTimeout to simulate delayed API calls...
setTimeout(() => {
this.cats = [
{ href: 'https://google.com' },
{ href: 'https://microsoft.com' },
{ href: 'https://apple.com' },
{ href: 'https://amazon.com' },
];
this.cats.forEach((cat, i) => {
setTimeout(() => {
const data = { href: cat.href };
this.$set(this.tools, cat.href, data); // <-- use this.$set for dynamic property addition
}, i * 1000);
})
}, 1000);
}
}
})
<script src="https://unpkg.com/vue@2.5.17"></script>
<div id="app">
<div v-if="!cats || cats.length == 0">Loading...</div>
<div v-for="cat in cats" :key="cat.href" v-else>
<table>
<tr v-for="tool in tools[cat.href]" :key="tool.href">
<td>cat.href: {{cat.href}}</td>
</tr>
</table>
</div>
<pre>tools: {{tools}}</pre>
</div>

最新更新