如何在Vue 3和Bootstrap 5轮播中停止除活动视频外的所有视频播放?

5n0oy7gb  于 2023-05-01  发布在  Vue.js
关注(0)|答案(1)|浏览(104)

我正在使用Vue 3、TypeScript和电影数据库(TMDB)开发SPA。我也使用Bootstrap 5作为UI。
为了在电影详细信息页面上显示电影预告片,我制作了TrailerCarousel.vue组件:

<template>
  <div
    id="trailersCarousel"
    class="carousel slide"
    data-bs-interval="false"
  >
    <ol v-if="movieTrailers.length > 1" class="carousel-indicators">
      <li
        v-for="(video, index) in movieTrailers.slice(0, maxCarouselItems)"
        :key="video.id"
        data-bs-target="#trailersCarousel"
        :data-bs-slide-to="`${index}`"
        :class="{ active: index === 0 }"
      >
        {{ index + 1 }}
      </li>
    </ol>

    <div class="carousel-inner">
      <div
        v-for="(video, index) in movieTrailers.slice(0, maxCarouselItems)"
        :key="video.id"
        class="carousel-item"
        :class="{ active: index === 0 }"
      >
        <iframe
          class="embed-responsive-item"
          :src="`https://www.youtube.com/embed/${video.key}`"
        ></iframe>
      </div>
    </div>

    <button
      v-if="movieTrailers.length > 1"
      class="carousel-control-prev"
      type="button"
      data-bs-target="#trailersCarousel"
      data-bs-slide="prev"
    >
      <span class="carousel-control-prev-icon"></span>
    </button>

    <button
      v-if="movieTrailers.length > 1"
      class="carousel-control-next"
      type="button"
      data-bs-target="#trailersCarousel"
      data-bs-slide="next"
    >
      <span class="carousel-control-next-icon"></span>
    </button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "TrailerCarousel",

  props: {
    movieTrailers: Array,
  },

  data() {
    return {
      maxCarouselItems: 5
    } 
  },
});
</script>

<style scoped lang="scss">
.carousel-indicators {
  li {
    text-indent: 0;
    margin: 0 2px;
    font-size: 12px;
    width: 26px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border: none;
    border-radius: 50%;
    color: #333;
    background-color: #fff;
    transition: all 0.25s ease;
    &.active,
    &:hover {
      margin: 0 2px;
      background-color: #0b8a52;
      color: #fff;
    }
  }
}

.carousel-control-next,
.carousel-control-prev {
  width: 7.5%;
}

.carousel-item {
  padding-top: 56.25%;
  height: 0px;
  position: relative;
}

iframe {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>

我在src\components\MovieDetails.vue中使用上面的组件:

<div v-if="movieTrailers.length" class="mb-3">
    <h2 class="section-title">Trailers</h2>
    <TrailerCarousel :movieTrailers = "movieTrailers" />
</div>

问题
当从一个预告片导航到另一个预告片并播放它们时,* 先前播放的预告片不会停止 * 并且它们重叠。
我无法找到一种方法来防止这种情况。

什么是实现预期结果的可靠方法?

相关问题