1. 程式人生 > 其它 >Vue.js3: 頁面開啟前實現圖片全部預載入([email protected])

Vue.js3: 頁面開啟前實現圖片全部預載入([email protected])

一,js程式碼:

1,html程式碼

  <div ref="loadingDiv" v-show="loadingShow" style="left:0;top:0;position:fixed;width:100vw;height:100vh;background: #000000;opacity: 0.7;z-index:65535;">
    <div style="font-size:0.5rem;text-align:center;width:3rem;height:1rem;color:#ffffff;position:absolute;left:calc(50vw - 1.5rem);top:calc(50vh - 0.5rem);"
> loading:{{loadingProcess}}% </div> </div>

2, js程式碼

    //已載入完成的數量 
   const loadCount = ref(0);
    //執行下載所有圖片
    const loadImages = ()=> {
      let imgs = [
        "static/image/xiaolanyuan.png",
        "static/ani/fzlc.png",
        "static/ani/ship.jpg",
        "static/image/slide6/27.jpg",
        
"static/image/slide6/28.jpg", "static/image/slide6/29.jpg", "static/image/31.png", "static/image/32.png", "static/image/tzms.png", "static/image/ztjjjms.png", "static/image/dahongyuan.png", ] for (let img of imgs) { let image = new Image() image.src
= img image.onload = () => { console.log("image.onload:length:"+imgs.length); console.log("image.onload:src:"+image.src); loadCount.value++ // 計算圖片載入的百分數,繫結到percent變數 let percentNum = Math.floor(loadCount.value / imgs.length * 100) loadingProcess.value = percentNum; //判斷是否結束 if (loadCount.value >= imgs.length) { //loading end console.log('end:'+loadingProcess.value); loadingShow.value = false; } } } }

呼叫:

    onMounted(()=>{
      loadImages();
    })
    //載入的百分比
    const loadingProcess = ref("0");
    //是否顯示
    const loadingShow = ref(true);

    return {
      loadingProcess,
      loadingShow,
    }

二,檢視效果

三,檢視vue的版本:

liuhongdi@lhdpc:/data/vue/guotou4$ npm list vue
guotou4@0.1.0 /data/vue/guotou4
├─┬ @vue/cli-plugin-babel@5.0.4
│ └─┬ @vue/babel-preset-app@5.0.4
│   └── vue@3.2.33 deduped
├─┬ @vueuse/core@8.4.2
│ ├─┬ @vueuse/shared@8.4.2
│ │ └── vue@3.2.33 deduped
│ ├─┬ vue-demi@0.12.5
│ │ └── vue@3.2.33 deduped
│ └── vue@3.2.33 deduped
├─┬ vue@3.2.33
│ └─┬ @vue/server-renderer@3.2.33
│   └── vue@3.2.33 deduped
└─┬ vue3-count-to@1.1.2
  └── vue@3.2.33 deduped