所以我在这个vue页面中嵌入了video.js视频播放器。我有一个播放列表组件,该组件在每次当前视频结束时都会更新。
问题是,当更新此组件时,会调用created()
,并将视频播放器的源设置为第一个播放列表项。
为什么重新渲染页面中的组件时为什么会调用created?
这里是代码:
<template>
<div class="container">
<div
class="video-player-box vjs-16-9 video"
v-if="sourceList[0]"
@ended="onPlayerEnd($event)"
v-video-player:myVideoPlayer="playerOptions">
</div>
<Playlist :currentSourceIndex="currentSourceIndex"/>
</div>
</template>
<script>
import Vue from 'vue'
import Playlist from '../components/playlist'
const API_URL = 'http://localhost:5000/';
export default {
components: {
Playlist,
},
data() {
return {
sourceList: [], // array of video sources populated by API
currentSourceIndex: 0, // index of the current video being played
playerOptions: {
sources: [
{
type: 'video/mp4',
src: ""
}
]
}
}
},
methods: {
onPlayerEnd(player) {
this.currentSourceIndex++
const nextSource = this.sourceList[this.currentSourceIndex];
player.src(nextSource);
player.play();
}
},
created() {
if (process.browser) {
const VueVideoPlayer = require('vue-video-player/dist/ssr')
Vue.use(VueVideoPlayer)
}
fetch(API_URL + this.$route.query.game)
.then( res => res.json() )
.then(apiData => {
this.sourceList = apiData.map((d => d.url)).reverse()
this.playerOptions.sources[0].src = this.sourceList[0]
})
}
}
</script>
[视频结束时,会调用onPlayerEnd(player)
,将currentSourceIndex
更新为this.currentSourceIndex++
,这又会重新渲染播放列表组件<Playlist :currentSourceIndex="currentSourceIndex"/>
。
现在一切都很好,但是当重新渲染此组件时,由于某些原因调用created()
,这会将玩家的来源设置为第一个播放列表项this.playerOptions.sources[0].src = this.sourceList[0]
。
如果我从:currentSourceIndex="currentSourceIndex"
中删除<Playlist/>
,则视频结束时不会调用created()
。现在,这真的使我感到困惑,在重新渲染子组件时调用created()
的预期行为是吗?
为什么没有生命周期钩只被调用一次?这是Vue的缺点吗?希望我有道理。
尝试用v-show替换v-if