通用的Vue 2.x 组件级懒加载解决方案(Vue Lazy Component ),非常适合长页面加载。
下面的代码这是推迟了模块的渲染和模块内的资源的加载
,如果我们需要更进一步,连模块本身的代码也是懒加载,就像 AMD 那样异步按需加载,这个将在第二部分尝试。
css
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
}
#header{
height:2000px;
background-color: #e3e4e2;
}
#floor1{
height:200px;
background-color: #e46690;
}
#floor2{
height:200px;
background-color: #f1f106;
}
#floor3{
height:200px;
background-color: #06f1f1;
}
App.vue
<template>
<div id="app">
<Header>
</Header>
<Floor id="floor1"/>
<Floor id="floor2"/>
<Floor id="floor3"/>
</div>
</template>
<script>
import '@/assets/css/main.css'
import Header from './components/Header'
import Floor from './components/Floor'
export default {
name: 'App',
data(){
return{
title:"this is a title",
}
},
methods:{
},
components: {
Header,
Floor
}
}
</script>
Floor.vue
<template>
<vue-lazy-component threshold="200px" @init="init" >
<div>this is floor</div>
<div slot="skeleton">
this is skeleton
</div>
</vue-lazy-component>
</template>
<script>
import { component as VueLazyComponent } from '@xunlei/vue-lazy-component'
export default{
methods:{
init(){
for(var i=0;i<100000;i++){
for(var j=0;j<1000;j++){
j+=1;
j-=1;
}
}
console.log('初始化中...');
}
},
components: {
'vue-lazy-component': VueLazyComponent
}
}
</script>