众所周知vue项目通常首屏加载会非常慢,在浏览器加载资源时,可以在首屏加入一个loading页面。
首先找到在根目录下的/pulic/index.html:
在index.html中找到我们的id为app的div元素:
示例修改如下:
<!-- public/index.html --><!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width,initial-scale=1.0" /><link rel="icon" href="<%= BASE_URL %>favicon.ico" /><title><%= htmlWebpackPlugin.options.title %></title><style>html,body,#app {height: 100%;margin: 0px;padding: 0px;}body {background-color: #f4f5f5;}.chromeframe {margin: 0.2em 0;background: #ccc;color: #000;padding: 0.2em 0;}</style><!-- loading --><style>#loading {width: 100vw;height: 100vh;background-color: #409eff;display: flex;align-items: center;justify-content: center;}.load_title {font-size: 22px;color: #fff;font-weight: bold;}</style></head><body><noscript><strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't workproperly without JavaScript enabled. Please enable it tocontinue.</strong></noscript><div id="app"><div id="loading"><p class="load_title">正在加载系统资源,请耐心等待...</p></div></div><!-- built files will be auto injected --></body></html>
这样就实现了一个简单的首屏加载页面:
在资源加载完后,就会转到正式的页面了。
具体的实现原理是Vue加载完项目之前,不会将dom元素放在app这个div内,html渲染出,Vue的资源还在加载,加载完成后会写入app下,从而顶替掉其中的loading页面内容。
可以在网上找一些加载的css动画等,放入加载页中,使页面看起来更美观。