# 骨架屏
# 知识点
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
1
2
3
4
5
2
3
4
5
$mount('#app') 会用App.vue里面的内容替换掉 <div id="app"></div>,
这就是为啥不能 $mount('body') 或者$mount('html')
# 原理
$mount('#app') 会 替换<div id="app"></div>的内容,
所以我们可以把骨架提前写入到 index.html 的<div id="app"></div>内部。
当在加载页面组件的时候显示骨架,页面加载完后,用App.vue的内容替换该标签内容。
# 方式一
使用 vue-skeleton-webpack-plugin (opens new window) 插件.
优点: 简单
缺点:只有首页才可以,骨架是写死的。
# 安装
npm install vue-skeleton-webpack-plugin -D
# 新建 skeleton.js
在 src/utils/目录下新建skeleton.js
import Vue from 'vue';
import Skeleton from '../components/Skeleton/Skeleton';
export default new Vue({
  components: {
    Skeleton,
  },
  render: h => h(Skeleton),
});
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 新建 Skeleton.vue
在 src/components/Skeleton目录下新建Skeleton.vue
<template>
  <div class="skeleton">
    <div class="skeleton-head"></div>
    <div class="skeleton-body">
      <div class="skeleton-title"></div>
      <div class="skeleton-content"></div>
    </div>
  </div>
</template>
<style>
.skeleton {
  padding: 10px;
}
.skeleton .skeleton-head,
.skeleton .skeleton-title,
.skeleton .skeleton-content {
  background: rgb(194, 207, 214);
}
.skeleton-head {
  width: 100px;
  height: 100px;
  float: left;
}
.skeleton-body {
  margin-left: 110px;
}
.skeleton-title {
  width: 500px;
  height: 60px;
  transform-origin: left;
  animation: skeleton-stretch 0.5s linear infinite alternate;
}
.skeleton-content {
  width: 260px;
  height: 30px;
  margin-top: 10px;
  transform-origin: left;
  animation: skeleton-stretch 0.5s -0.3s linear infinite alternate;
}
@keyframes skeleton-stretch {
  from {
    transform: scalex(1);
  }
  to {
    transform: scalex(0.3);
  }
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# vue.config.js配置
const path = require('path')
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin');
module.exports = {
    css: {
         extract: true, // css拆分ExtractTextPlugin插件,默认true - 骨架屏需要为true
    },
    configureWebpack: (config)=>{
        // vue骨架屏插件配置
        config.plugins.push(new SkeletonWebpackPlugin({
          webpackConfig: {
            entry: {
              app: path.join(__dirname, './src/utils/skeleton.js'),
            },
          },
          minimize: true,
          quiet: true,
        }))
  },
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 方式二
page-skeleton-webpack-plugin (opens new window) 饿了么的 PWA 升级实践 (opens new window)
# 方式三 一种自动化生成骨架屏的方案 (opens new window)
# 文档
← Vue 预渲染首屏优化 Vue CLI指南 →