Vue CLI:中播放視頻音頻組件MediaElement
最近更新時間 2020-03-13 23:09:22
在 Vue CLI 項目中播放視頻和音頻可以使用 MediaElement.js 。
1. 添加 MediaElement.js
在項目中添加 MediaElement.js 可以使用 npm 或者 yarn,如下所示:
npm install mediaelement
OR
yarn add mediaelement
2. 封裝 Vue 組件
新建組件文件 VideoPlayer.vue,如下所示:
<template>
<video
:width="width"
:height="height"
:preload="preload"
:autoplay="autoplay"
playsinline
webkit-playsinline
></video>
</template>
<script>
import 'mediaelement'
export default {
name: 'VideoPlayer',
props: {
source: {
type: String,
required: true,
default: ''
},
width: {
type: String,
required: false,
default: '640'
},
height: {
type: String,
required: false,
default: '360'
},
preload: {
type: String,
required: false,
default: 'none'
},
autoplay: {
type: Boolean,
required: false,
default: false
}
},
data() {
return {}
},
methods: {},
mounted() {
global.vbus.$emit('console', 'video mount')
const { MediaElementPlayer } = global
const vThis = this
// eslint-disable-next-line no-new
new MediaElementPlayer(this.$el, {
success: function(mediaElement, originalNode, instance) {
instance.setSrc(vThis.source)
if (vThis.autoplay) {
mediaElement.addEventListener('canplay', function() {
instance.play()
})
}
}
})
},
source: function(src) {
this.player.setSrc(src)
this.player.setPoster('')
this.player.load()
}
}
</script>
<style type="stylesheet/scss" lang="scss" scoped>
@import '~mediaelement/build/mediaelementplayer.min.css';
</style>