vue3开发的H5多个视频播放

92 阅读1分钟

vue3开发的H5多个视频播放

  <div class="video-list-container">
    <h1>视频列表</h1>
    <div class="video-list">
      <div v-for="(video, index) in videos" :key="video.id" class="video-item">
        <h3>{{ video.title }}</h3>
        <div class="video-wrapper">
          <video :ref="setVideoRef" :src="video.src" :poster="video.poster" controls playsinline webkit-playsinline
            x5-playsinline @play="handlePlay(index)"></video>
        </div>
        <p class="video-desc">{{ video.desc }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue'

// 视频数据
const videos = ref([
  {
    id: 1,
    title: '美丽风景',
    src: 'https://vjs.zencdn.net/v/oceans.mp4',
    poster: 'https://pic3.zhimg.com/v2-a227df7bf1ec78bd43f268033552b6d6_1440w.jpg',
    desc: '欣赏大自然的美丽风光'
  },
  {
    id: 2,
    title: '城市夜景',
    src: 'https://vjs.zencdn.net/v/oceans.mp4',
    poster: 'https://pic3.zhimg.com/v2-a227df7bf1ec78bd43f268033552b6d6_1440w.jpg',
    desc: '繁华都市的夜晚灯光秀'
  },
  {
    id: 3,
    title: '动物世界',
    src: 'https://vjs.zencdn.net/v/oceans.mp4',
    poster: 'https://pic3.zhimg.com/v2-a227df7bf1ec78bd43f268033552b6d6_1440w.jpg',
    desc: '可爱的野生动物们'
  }
])

// 存储所有video元素的引用
const videoElements = ref([])

// 设置video引用
const setVideoRef = (el) => {
  if (el) {
    videoElements.value.push(el)
  }
}

// 当前播放的视频索引
let currentPlayingIndex = null

// 处理播放事件
const handlePlay = (index) => {
  // 如果已经有视频在播放,且不是当前点击的视频,则暂停其他视频
  if (currentPlayingIndex !== null && currentPlayingIndex !== index) {
    videoElements.value[currentPlayingIndex].pause()
  }

  // 更新当前播放的视频索引
  currentPlayingIndex = index
}

// 组件卸载前暂停所有视频
onBeforeUnmount(() => {
  if (currentPlayingIndex !== null) {
    videoElements.value[currentPlayingIndex].pause()
  }
})
</script>

<style scoped>
.video-list-container {
  max-width: 100%;
  padding: 15px;
  box-sizing: border-box;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
}

.video-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.video-wrapper {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
  /* 16:9 比例 */
}

video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
}

h3 {
  padding: 10px 15px 0;
  margin: 0;
  font-size: 18px;
}

.video-desc {
  padding: 0 15px 15px;
  margin: 5px 0 0;
  color: #666;
  font-size: 14px;
}
</style>