首页 > 解决方案 > 仅在选定项目的 vue.js 模板中隐藏和显示 div?

问题描述

我有一系列歌曲,在模板内我有一个图标可以在 div 的显示/隐藏之间切换。它在单击时起作用,它会扩展 div,但它会为数组中的每个项目扩展 div(无论单击哪首歌曲)。我希望它只扩展单击项目的 div。我是否需要以某种方式将其链接到 id 变量?这是代码:

这是在 html 模板中:

<div class="dropdown-icon" title="Show/Hide Description" 
@click="toggleShowDescription">
<i class="icon ion-ios-arrow-dropdown-circle"></i>
</div>

<div :class="showDescription?'show':'hide'" v-if="showDescription">
<p class="song-description">{{song.description}}</p>

这是我在 JS 中关于隐藏/显示 div 元素的内容:

    songs: [

        {
        id: 1,
        title: "Track 1",
        description: "Description 1",
        url: "",
        keywords:"",
        genre:"",
        moods:"",
        tempo:"",
        theme:"",
      },

      {
        id: 2,
        title: "Track 2",
        description: "Description 2",
        url:"",
        keywords: "",
        genre:"",
        moods:"",
        tempo:"",
        theme:"",
      },
],

showDescription: false,
  },

methods: {

    toggleShowDescription() {
      this.showDescription = !this.showDescription;
    },

},

标签: javascripthtmlvue.js

解决方案


您正在为每首歌曲使用 showDescription 的值。最好的办法是创建一个数组来跟踪正在显示的歌曲描述,然后在单击切换按钮时添加/删除项目。

对于模板...

<div class="dropdown-icon" title="Show/Hide Description" 
@click="toggleShowDescription(song)">
<i class="icon ion-ios-arrow-dropdown-circle"></i>
</div>

<div :class="showDescription?'show':'hide'" v- 
if="songsDisplayingDescription.indexOf(song.id) !== -1">
<p class="song-description">{{song.description}}</p>

然后脚本...

  songsDisplayingDescription: [],
},
methods: {
  toggleShowDescription(song) {
    const songId = song.id;
    const indexOfSongId = this.songsDisplayingDescription.indexOf(songId);

    if (indexOfSongId !== -1) {
      this.songsDisplayingDescription.splice(indexOfSongId, 1);
      return;
    }

    this.songsDisplayingDescription.push(songId);
  }
}

推荐阅读