zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Vue.js3: 页面打开前实现图片全部预加载(vue@3.2.33)

Vue 实现 图片 页面 加载 打开 全部 3.2
2023-09-14 08:59:32 时间

一,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,
    }

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,查看效果

三,查看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