我有一个搜索框,当用户输入艺术家姓名时,它会显示与用户输入相匹配的艺术家列表。
我想在搜索中的艺术家姓名旁边显示艺术家图像。
我有一个包含以下内容的对象。艺术家姓名作为键,图像路径作为值
Radiohead: 'path_to_image',
Elliott Smith:'path_to_image'
我有一个计算属性,可以过滤艺术家姓名以供搜索。
computed: {
filteredArtists() {
return Object.keys(this.artistsList).filter((artist) => {
return artist.match(this.artistName)
})
}
},
在我的模板中,我正在遍历这些值
<ul class="searchFliter" v-for="artist in filteredArtists">
<li v-text="artist"></li>
</ul>
我找不到用计算值来管理它的方法。我可以轻松地遍历我的对象并显示艺术家姓名和艺术家图像,但无法对其进行过滤。
提前致谢
最佳答案
如果您想坚持自己的数据结构,那么您可以通过多种方式来显示图像以及匹配的艺术家。由于您实质上是在计算属性中获取 artistList
对象的键列表,因此您可以使用该键通过 artistList[artist]
获取路径。
<ul class="searchFliter" v-for="artist in filteredArtists">
<li>{{artist}} <img :src="artistList[artist]"></li>
</ul>
但是,如果您想像帖子标题中建议的那样,从列表中返回多个值,那么您可以更改计算属性。
filteredArtists() {
let matches = return Object.keys(this.artistsList).filter((artist) => {
return artist.match(this.artistName)
})
return matches.map(m => ({name: m, imagePath: this.artistsList[m]}))
}
此处的计算属性是查找所有匹配项,然后创建一个包含名称和图像路径的新对象。像这样在模板中使用它:
<ul class="searchFliter" v-for="artist in filteredArtists">
<li>{{artist.name}} <img :src="artist.imagePath"></li>
</ul>
当然,你也可以选择不同的数据结构。为什么不使用艺术家对象数组?
[
{name: "Radiohead", imagePath: "path to image"},
{name: "Elliott Smith", imagePath: "path to image"}
]
在这种情况下,你的计算属性就变成了
filteredArtists() {
return this.artistsList.filter(m => m.name.match(this.artistName))
}
关于javascript - 从 Vue JS 中的计算过滤器返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46025443/