vue.js 如何删除JSON文件中的空字符串?

zujrkrfu  于 2023-05-29  发布在  Vue.js
关注(0)|答案(1)|浏览(312)

Nuxt从JSON接收空字符串时返回错误:
示例错误:

input must be a string (received string: "")

我在Nuxt中的循环示例:

<Grid class="sponsors">
  <Img v-for="prop in home" :src="prop.sponsors" :width="300" />
</Grid>

JSON内容:

[
{
"id": "1",
"title": "Film",
"desc": "Film desc",
"sponsors": "sponsors/culture-fond_ftl1iu_nhpivj.png",
"films": "film 1"
},
{
"id": "2",
"title": "",
"desc": "",
"sponsors": "sponsors/muzey-tavrida-bw_wedmvw_qf4ixd.png",
"films": "film 2"
},
{
"id": "3",
"title": "",
"desc": "",
"sponsors": "sponsors/insightstudio-logo-white_rc0vme.png",
"films": "film 3"
},
{
"id": "4",
"title": "",
"desc": "",
"sponsors": "",
"films": "film 4"
},
{
"id": "5",
"title": "",
"desc": "",
"sponsors": "",
"films": "film 5"
},
{
"id": "",
"title": "",
"desc": "",
"sponsors": "",
"films": "film 6"
}
]

如何从JSON中删除空字符串?或者如何忽略这个错误?
我使用Nuxt 3.4.1

5uzkadbs

5uzkadbs1#

多种方法来解决这个问题。
您可以在JavaScript中使用filter()(或者在其他框架中使用类似的东西)

const filteredData = jsonData.filter(obj => Object.values(obj).some(val => val !== ""));

另一种解决方法是在Nuxt中渲染IMG组件之前检查空字符串。

<Grid class="sponsors">
  <Img v-for="prop in home" :src="prop.sponsors" :width="300" v-if="prop.sponsors !== ''" />
</Grid>

相关问题