[英]how load video only once if a modal is dynamic in vuejs3/vite?
我在優化 Vuejs3/Vite 和 Aframe 中構建的應用程序的性能時遇到問題。 我需要以某種方式預取 6 個視頻。 問題是每次我打開一個模式時,瀏覽器都會再次獲取一個視頻。 我希望瀏覽器只獲取一次並以某種方式存儲它。
我的應用程序應該是這樣的。 主頁有 6 個按鈕。 單擊時,每個按鈕都會打開一個模式。 在模態中有 6 個視頻。 因此,當用戶單擊第二個按鈕時,模式會打開,其中只有第二個視頻自動播放。 當用戶單擊“關閉”按鈕時,模式關閉並且視頻暫停。
現在我的代碼看起來像這樣:HTML 模板
// 6 button-images like this
<a-image
class="link"
src="/play-new.png"
sound="on: click; src: #click-sound"
@click="openVideo(0)"
position="-5 1.5 -4.5"
rotation="0 60 0"
></a-image>
// Modal
<div
v-show="isModalOpen"
class=""
<div v-for="(video, i) in videos" :key="i">
<video :src="video.file" loop class="block" :class="i === currentVideo ? 'play' : 'hidden'" v-show="$nextTick(() => i === currentVideo && play(i))" />
<div class="">
<button @click="hideVideo" class="">X</button>
</div>
</div>
</div>
我的 JS:
<script setup>
import { ref } from 'vue'
const videos = [ {
file: 'videos/1.mp4',
},
{
file: 'videos/2.mp4'
},
{
file: 'videos/3.mp4'
},
{
file: 'videos/4.mp4'
},
{
file: 'videos/5.mp4'
},
{
file: 'videos/6.mp4'
}
];
const currentVideo = ref(-1);
const isModalOpen = ref(false);
function openVideo(videoIndex) {
currentVideo.value = videoIndex; //videos[videoIndex].file;
isModalOpen.value = true;
}
function hideVideo() {
document.querySelector('.play').pause();
currentVideo.value = -1;
isModalOpen.value = false;
}
function play(index) {
if (index == currentVideo.value) {
document.querySelector('.play').play();
return true;
}
return false;
}
</script>
這是我重新啟動頁面並打開模式后我的網絡選項卡的樣子。 初始負載為紅色。 模態打開是綠色的。
到目前為止我已經嘗試過:而不是v-if
我讓它與v-show
一起工作,因為使用 v-if 它根本沒有被獲取。
總而言之,我如何讓瀏覽器只加載一次視頻並緩存/存儲它。
用<keep-alive>
包裝你的組件應該可以工作:
// Modal
<div
v-show="isModalOpen"
class=""
<div v-for="(video, i) in videos" :key="i">
<keep-alive>
<video :src="video.file" loop class="block" :class="i === currentVideo ? 'play' : 'hidden'" v-if="$nextTick(() => i === currentVideo && play(i))" />
</keep-alive>
<div class="">
<button @click="hideVideo" class="">X</button>
</div>
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.