子组件 : nbLoading 文件:
<template>
<div class="nb-loading">
<div class="nb-loading-process">
<div class="process">
<img src="@/common/images/1-3@2x.png" />
<span>{{ process }}%</span>
</div>
<div class="desc">加载中,敬请期待…</div>
</div>
</div>
</template>
props:{
process:{
type:[Number ,String],
default:0
}
},
watch: {
// 如果val为100代表加载成功
process(val) {
if ( Number(val) === 100) {
this.$emit('success');
}
}
},
父组件: Home文件
<div>
<div class="page-list">
<template v-for="item in config">
<component
:process="process"
>
</component>
</template>
</div>
<div id="imglist" style="width:0;height:0;overflow:hidden;"></div>
</div>
import nbLoading from '@/components/nb-loading';
import { modeles2x } from '@/common/imageList.js';
components: {
nbLoading,……,……,……,
},
data() {return {
imagesList: modeles2x,
imageCount: 0, // 图片数
loadCount: 0, // 已经加载的图片数?
config: [
{
name: 'nb-loading',
id: 0,
logo
}, ……………………],
getData: 0, // 页面数据一开始置为0,只有获取到数据之后才置为1
}}
computed: {
process() {
if (!this.imageCount) return 0;
let value = Math.floor((this.loadCount / this.imageCount) * 99); // 图片加载完最多为 1*99=99
return isNaN(value) ? 0 : value + this.getData; // 再加上(确保必须是)等页面数据加载完后的数据 1+99=100
}
},
created() {
this.query(); // 获取页面数据
},
mounted() {
this.hanlderLoading(); // 加载静态资源
},
methods: {
query() {
this.$api.getannualData().then((res) => {
if (Object.keys(res.body)) {
this.reportData = res.body;
this.getData = 1; // 只有获取数据之后才置为1
}
});
},
hanlderLoading() {
this.imageCount = this.imagesList.length;
const _that = this;
this.imagesList.forEach((element) => {
const url = require('@/common/' + element + '.png');
var img = document.createElement('img');
img.style.background = `url(${url})`;
document.getElementById('imglist').appendChild(img);
img.src = url;
img.onload = function() {
_that.loadCount++;
};
});
},
}
imageList.js文件
// 处理图片 1/2/3倍图
const modulesFiles = require.context('./images', true, /\.png$/);
const modulesFiles2 = require.context('./imgs', true, /\.png$/);
const modules = [];
const modeles2x = [];
const modeles3x = [];
const pushFileName = (obj = {}, path) => {
obj.keys().forEach((modulePath) => {
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1');
if (RegExp(/@2x/).test(moduleName)) {
modeles2x.push(path + moduleName);
} else if (RegExp(/@3x/).test(moduleName)) {
modeles3x.push(path + moduleName);
} else {
modules.push(path + moduleName);
}
});
};
pushFileName(modulesFiles, 'images/');
pushFileName(modulesFiles2, 'imgs/');
export { modules, modeles2x, modeles3x };