You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue v-for循环中点击播客项显示对应Spotify iframe的JS实现

播客点击展开Spotify嵌入实现方案

原有方案缺陷说明

CSS :active 伪类仅匹配元素被鼠标按压、按键激活的瞬时状态,交互动作结束(鼠标松开)后状态会立即重置,无法实现持久的显隐切换效果,这类需要长期保留的UI状态必须通过JS响应式状态控制。

具体实现步骤(基于Vue响应式逻辑,适配现有v-for结构)

  • 新增响应式状态记录当前激活的播客项索引,默认值设为-1,代表初始状态无展开项
    • Options API写法:
      data() {
        return {
          // 其余原有业务状态保留
          activePodcastIndex: -1
        }
      }
      
    • Composition API写法:
      import { ref } from 'vue'
      const activePodcastIndex = ref(-1)
      
  • 删除原有依赖:active的CSS显隐规则,避免和新逻辑冲突
  • 修改模板代码,给播客项绑定点击事件,同时通过v-show绑定显隐逻辑:
    <div
      v-for="(podcast, index) in content.podcasts"
      :key="index"
      class="swiper-slide"
    >
      <PodcastsItem
        :imageUrl="podcast.image"
        :title="podcast.name"
        :text="'Duur: ' + podcast.id + ' ms'"
        class="podcast_item"
        @click="activePodcastIndex = activePodcastIndex === index ? -1 : index"
        v-show="activePodcastIndex !== index"
      />
      <iframe
        style="border-radius:12px"
        :src="activePodcastIndex === index ? 'https://open.spotify.com/embed/episode/' + podcast.id + '?utm_source=generator' : ''"
        width="100%"
        height="232"
        frameBorder="0"
        allowfullscreen=""
        allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
        v-show="activePodcastIndex === index"
      ></iframe>
    </div>
    

优化说明

  • 用v-show而非v-if控制显隐:不会重复销毁、重建iframe元素,避免切换时重复加载Spotify资源,交互更流畅
  • iframe的src仅在对应项激活时才赋值:初始状态下不会加载所有播客的嵌入资源,减少首屏请求量,打开速度更快
  • 现有逻辑已支持点击同一项自动收回嵌入内容,若需要在iframe展示时点击iframe区域也能收回,可给iframe额外绑定相同的点击切换逻辑即可

内容的提问来源于stack exchange,提问作者Erik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 03:31:01