仅在选定项目的vue.js模板中隐藏并显示div?

时间:2019-04-22 16:11:48

标签: javascript html vue.js

我有一组歌曲,并且在模板内有一个图标,用于在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中有关hide / show 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;
    },

},

1 个答案:

答案 0 :(得分:1)

您正在为每首歌曲使用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);
  }
}