vue单页面解决多个视频同时仅能播放一个问题

封装一个媒体播放的列表组件,里面包含图集和视频。为了代码解耦,将图集组件,和视频播放组件分离出来。在这里仅记录一下视频播放遇到的问题。在列表数据里面可能有多个视频,循环渲染列表,这里仅简述多视频播放,要求一次只能播放一个的问题。

列表渲染
<template>
  <div class="case-container">
    <div class="case-list">
      <div class="case-item" v-for="item in caseList" :key="item.id">
        <video-card :src="item.src" :poster="item.src"></video-card>
        <!--<images-card></images-card>-->
      </div>
    </div>
  </div>
</template>

<script>
import VideoCard from './videoCard'
// import ImagesCard from './imagesCard'
export default {
  components: {
    VideoCard
    // ImagesCard
  },
  props: {
    caseList: {
      type: Array,
      default: () => []
    }
  }
}
</script>

<style lang="less" scoped>
</style>
视频组件封装

视频组件封装十分常规,用到了video标签,支持手动控制播放暂停。如果要支持播放下一个视频前前面的播放的视频暂停,只能手动去触发其他video标签的pause方法。因为是多组件通信,无法获取其他video的DOM,所以跨组件通信。this.$bus,值得拥有

<template>
  <div class="video-container">
    <video
      v-if="isPlay"
      ref="video"
      class="video"
      controls
      :src="src"
      :poster="poster"
      :autoplay="isPlay"
      @touchmove.prevent
      @pause="pause"
      @play="play"
      @ended="pause"
      webkit-playsinline="true"
      playsinline="true"
    ></video>
    <div v-if="disabled" class="cover-outer"></div>
    <!--自定义播放按钮-->
    <div
      v-if="!isPlay"
      class="cover center-flex"
      :style="poster ? {backgroundImage: `url(${poster})`} : {}"
    >
      <img
        @click="play"
        src="xxx"
        class="play-icon"
      />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      default: ''
    },
    poster: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isPlay: false,
      disabled: true
    }
  },
  mounted() {
    this.$bus.$on('stopVideo', this.pause) // 子组件接受数据
  },
  beforeDestroy() {
    this.$bus.$off('stopVideo') // 销毁前清除事件监听
  },
  methods: {
    clearTimer() {
      this.timer && clearTimeout(this.timer)
    },
    play() {
      this.$bus.$emit('stopVideo') // 子组件发送数据
      this.clearTimer()
      this.isPlay = true
      // 防止点击穿透
      this.timer = setTimeout(() => {
        this.disabled = false
      }, 500)
      this.$nextTick(() => {
        this.$refs.video.play()
      })
    },
    pause() {
      this.clearTimer()
      this.isPlay = false
      this.disabled = true
    }
  }
}
</script>

<style lang="less" scoped>
// 样式省略
</style>
bus.js就是这么简单。创建之后挂载到app.js,通过this.$bus.$on,this.$bus.$emit去触发方法,具体使用见上。不知道怎么使用this.$bus可以去百度一下,网上教程很详细,不再赘述
import Vue from 'vue'

export default () => {
  Vue.prototype.$bus = new Vue()
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值