默认 vue 已经安装好了,UI 组件这里以 vux 为例,用什么 UI 库问题不大
注:循环这种实时视频的做法其实不推荐,但是你保不准,真的有这样的需要
1. 安装依赖 hls.js
npm i hls.js -S
2. 使用
2.1 html 循环渲染 video 节点
<div v-for="video in videos" :key="video.ref" class="videoList">
<p>
<span>XX 监控 </span>
<span> 通道{{video.which}}</span>
<span><x-button @click.native="playVideo(video.which)" mini> 播放 </x-button><span>
</p>
<div class="videoContainer">
<video :ref='video.ref'></video>
</div>
</div>
2.2【js】hls 挂载节点,解析
// 结构略
import Hls from 'hls.js';
data() {
return {videos: []
}
},
methods: {
// 节点挂载 ---$refs
attach() {for (let index = 0; index < this.videos.length; index++) {if (Hls.isSupported()) {this.videos[index].hls = new Hls();
this.videos[index].hls.attachMedia(this.$refs[this.videos[index].ref][0]);
}
}
},
// 播放实时监控
playVideo(channel) {
let _this = this;
let videoRef = this.videos[channel-2].ref;
this.$refs[videoRef][0].controls = 'controls';
// 请求和心跳等涉及业务的略
_this.videos[channel-2].hls.loadSource(res.data.url);
// 正常解析
_this.videos[channel-2].hls.on(Hls.Events.MANIFEST_PARSED, function () {_this.$refs[videoRef][0].play()});
// 失败
_this.videos[channel-2].hls.on(Hls.Events.ERROR, function () {根据业务对失败情况进行分别处理}
}
}
// 选择生命周期(需要 $el 已经存在,mounted()或者 keep-alive 的 activated())// 我这里使用的是 activated()
activated(){// axios 请求略(这里演示用固定数量,通道从 2 开始)
this.videos = [];
for (let i = 0; i < 5; i++) {
let item = {
hls: null,
ref: `video${i+2}`,
which: i+2,
}
this.videos.push(item)
this.$nextTick(() => {this.attach()
})
}
}
// 销毁
deactivated() {for (let i = 0; i < this.videos.length; i++) {this.videos[i].hls.destroy();}
}