vue3 实现页面静态资源预加载
·
Loading.vue(router.js中将默认路由设置为Loading.vue,静态图片资源加载完成后自动跳转至首页)
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
onMounted(() => {
// 预加载
preload()
})
const router = useRouter()
const count = ref(0)
const percent = ref('')
const preload = () => {
let chooseEat = import.meta.glob('../assets/img/*', { eager: true })
let listlength = Object.keys(chooseEat).length
for (const item in chooseEat) {
let image = new Image()
// 不使用的原因: new URL(url, import.meta.url):url为相对路径 Vite 生产环境不会转换,https://cn.vitejs.dev/guide/assets.html
// image.src = new URL(`${all[b].img}`, import.meta.url).href
image.src = chooseEat[item].default
// console.log(image.src)
// 图片加载
image.onload = () => {
count.value++
let percentNum = Math.floor((count.value / listlength) * 100)
percent.value = `${percentNum}%`
}
image.onerror = () => {
console.log('图片加载失败')
}
}
}
watch(percent, (newVal) => {
// console.log(newVal)
if (newVal === '100%') {
router.replace('/index')
}
})
</script>
<template>
<div class="loading box clmcenter">
<div class="progress">
<div class="progress-done" :data-done="count" :style="{ width: percent }"></div>
</div>
<div class="text">
loading...
{{ percent }}
</div>
</div>
</template>
<style lang="scss" scoped>
.loading {
font-size: 36px;
.progress {
background-color: #ffffff;
border-radius: 5px;
position: relative;
margin: 0 10px;
height: 10px;
width: 240px;
.progress-done {
background: linear-gradient(to left, rgba($color: #8651B9, $alpha: 1.0), rgba($color: #8651B9, $alpha: 0.3));
box-shadow:
0 2px 2px -3px rgb(255, 255, 255),
0 1px 5px rgb(255, 255, 255);
border-radius: 5px;
height: 10px;
width: 0;
transition: width 1s ease 0.3s;
}
}
.text {
margin-top: 30px;
}
}
</style>
更多推荐



所有评论(0)