作用
在Vue项目中,单页面项目在第一次加载的时候都会加载较多的资源,尤其管理系统等,如果不做加载动画进行提示,会出现较长的空白页面,对用户的体验不是很友好,这样的场景就需要使用加载动画进行体验优化
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<style>
#Loading {
top: 50%;
left: 50%;
position: absolute;
-webkit-transform: translateY(-50%) translateX(-50%);
transform: translateY(-50%) translateX(-50%);
z-index: 100;
}
@-webkit-keyframes ball-beat {
50% {
opacity: 0.2;
-webkit-transform: scale(0.75);
transform: scale(0.75);
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
@keyframes ball-beat {
50% {
opacity: 0.2;
-webkit-transform: scale(0.75);
transform: scale(0.75);
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
.ball-beat>div {
background-color: #279fcf;
width: 15px;
height: 15px;
border-radius: 100% !important;
margin: 2px;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
display: inline-block;
-webkit-animation: ball-beat 0.7s 0s infinite linear;
animation: ball-beat 0.7s 0s infinite linear;
}
.ball-beat>div:nth-child(2n-1) {
-webkit-animation-delay: 0.35s !important;
animation-delay: 0.35s !important;
}
#Loading {
font-size: 13px;
text-align: center;
}
</style>
<body>
<div id="Loading">
<div class="loader-inner ball-beat">
<div></div>
<div></div>
<div></div>
</div>
<p>初始化中</p>
</div>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
App.vue
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Hello Vue 3 + Vite" />
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue'
// This starter template is using Vue 3 experimental <script setup> SFCs
// Check out https://github.com/vuejs/rfcs/blob/master/active-rfcs/0040-script-setup.md
document.body.removeChild(document.getElementById('Loading'))
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
原理
使用CSS制作一个动画,在加载index.html
时就生效,隐藏其他内容的显示,在App.vue
加载时将动画关闭,显示正常内容,起到加载动画的效果,避免白屏加载的情况