从 Vue JS 中的计算过滤器返回多个值

Qai*_*udé 5 javascript vue.js vuejs2

我有一个搜索框,当用户输入艺术家姓名时,它会显示与用户输入匹配的艺术家列表。

我想在搜索中的艺术家姓名旁边显示艺术家图像。

我有一个包含以下内容的对象。艺术家姓名作为键和图像路径作为值

Radiohead: 'path_to_image',
Elliott Smith:'path_to_image'
Run Code Online (Sandbox Code Playgroud)

我有一个计算属性,可以过滤艺术家姓名以进行搜索。

computed: {
filteredArtists() {
  return Object.keys(this.artistsList).filter((artist) => {
    return artist.match(this.artistName)
  }) 
}
Run Code Online (Sandbox Code Playgroud)

},

在我的模板中,我正在迭代这些值

<ul class="searchFliter" v-for="artist in filteredArtists">
  <li v-text="artist"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我找不到用计算值来管理它的方法。我可以轻松地遍历我的对象并显示艺术家姓名和艺术家图像,但无法对其进行过滤。

提前致谢

Ber*_*ert 5

If you want to stick to your data structure then there are a number of ways you could manage to display the image along with the matching artists. Since you are essentially getting a list of keys to your artistList object in your computed property, you can use that key to get the path using artistList[artist].

<ul class="searchFliter" v-for="artist in filteredArtists">
  <li>{{artist}} <img :src="artistList[artist]"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

However, if you want to instead, as you suggest in the title of your post, return multiple values from the list, then you can alter the computed property.

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]}))
}
Run Code Online (Sandbox Code Playgroud)

Here the computed property is finding all the matches and then creating a new object containing the name and image path. Use it in the template like so:

<ul class="searchFliter" v-for="artist in filteredArtists">
  <li>{{artist.name}} <img :src="artist.imagePath"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Of course, you can also choose a different data structure as well. Why not use use an array of artist objects?

[
  {name: "Radiohead", imagePath: "path to image"},
  {name: "Elliott Smith", imagePath: "path to image"}
]
Run Code Online (Sandbox Code Playgroud)

In which case your computed property simply becomes

filteredArtists() {
  return this.artistsList.filter(m => m.name.match(this.artistName))
}
Run Code Online (Sandbox Code Playgroud)