- Published on
vue3 v-for无法获取Map里的对象数组
- Authors
- Name
- JiGu
- @crypto20x
运行环境
- vue3.2.33
- win10
- vite-plugin-ssr 我用了ssr插件,不知是否与这个有关。
出错代码如下
<div class="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-2 mt-4 max-w-7xl mx-auto">
<div v-for="item in animeContents.get(week[whichTab])" class="card w-40 bg-base-100 shadow-xl">
<figure><img src="https://placeimg.com/400/225/arch" alt="Shoes" /></figure>
<div class="card-body">
<h2 class="card-title">{{ item}}</h2>
<p>If a dog chews shoes whose shoes does he choose?</p>
</div>
</div>
</div>
setup js
const whichTab = ref(0)
const week = ref(
[
"周一",
"周二",
"周三",
"周四",
"周五",
"周六",
"周日",
"网络放送"
])
const animeContents = ref(new Map())
// animeContents 动态增加了对象,结构如下
animeContents.set(key, {
title: [],
img: []
})
v-for要迭代 **animeContents.get(key).title[]或animeContents.get(key).img[]**的值时,会出现 'title' undefined错误
解决方案
将title或者img的数组长度作为v-for循环的次数,通过 {{ animeContents.get(key).title.at(i) }}
来获取值,必须通过v-for k-v的方式迭代
<div class="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-2 mt-4 max-w-7xl mx-auto">
<template v-for="(v,k) in animeContents.get(week[whichTab])">
<template v-for="(vv,i) in v">
<div v-if="k == 'title'" class="card w-40 bg-base-100 shadow-xl">
<figure><img :src="animeContents.get(week[whichTab]).img.at(i)" alt="Shoes" /></figure>
<div class="card-body">
<h2 class="card-title">{{ animeContents.get(week[whichTab]).title.at(i) }}</h2>
</div>
</div>
</template>
</template>
</div>