简短的回答是:您不能在不丢失其状态的情况下移动 iframe DOM 节点,如in this answer 所述。
长答案是:您有其他选择。我认为您最好的选择是直接在“角落播放器”中播放视频,然后将其重新设置为页面的正确位置。为此,您需要自己与 DOM 进行一些交互,您可以通过在要显示视频的容器上设置 ref 轻松完成。
最后你会得到这样的结果:
在您的 App.vue 中,您有您的标准 router-view,以及一些将包含您的实际视频的元素。
<template>
<div id="app">
<router-view/>
<corner-player/>
</div>
</template>
您将开始播放视频的页面将包含一些占位符元素,作为放置视频的指导点:
<div class="player-container" ref="player"></div>
然后我们使用生命周期挂钩来获取正确的 url 和样式以发送给播放器。我使用简单的总线来更轻松地在应用程序中传递事件,否则将数据传输到播放器组件通常会很麻烦。我们使用安装的钩子来设置视频,因为那是第一个渲染周期发生的时候。 beforeDestroy 生命周期允许我们发送某种事件,将视频放在角落里。
export default {
name: "child1",
mounted() {
const container = this.$refs.player;
const boundingBox = container.getBoundingClientRect();
this.$bus.$emit("play-video", {
url: "https://www.youtube.com/embed/dW4HCi1zZh8",
styling: {
position: "absolute",
top: `${boundingBox.top}px`,
left: `${boundingBox.left}px`,
width: `${boundingBox.width}px`,
height: `${boundingBox.height}px`,
border: "3px dotted red"
}
});
},
beforeDestroy() {
this.$bus.$emit("move-to-corner-player");
}
};
然后播放器组件使用这两个事件并确保应用正确的样式。我不建议像在这里那样应用原始 css,但这是一个概念证明。
<template>
<div class="corner-player" :style="styling" v-if="url">
<iframe
width="1280"
height="540"
:src="url"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</div>
</template>
<script>
export default {
name: "CornerPlayer",
data() {
return {
styling: {},
url: "",
defaultStyling: {
border: "3px solid blue",
position: "fixed",
bottom: 0,
right: 0,
height: "150px",
width: "220px"
}
};
},
created() {
this.$bus.$on("play-video", this.playVideo);
this.$bus.$on("move-to-corner-player", this.moveToCornerPlayer);
},
beforeDestroy() {
// Prevent memory leaks
this.$bus.$off("play-video", this.playVideo);
this.$bus.$off("move-to-corner-player", this.moveToCornerPlayer);
},
methods: {
playVideo({ url, styling }) {
this.url = url;
this.styling = styling;
},
moveToCornerPlayer() {
this.styling = {
...this.defaultStyling
};
}
}
};
</script>
<style scoped>
iframe {
width: 100%;
height: 100%;
}
</style>
你可以在 Codesandbox 上玩这个: