常用的懒加载方式有两种:即使用vue异步组件 和 ES中的import
路由懒加载
未用懒加载,vue中路由代码如下
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component:HelloWorld
}
]
})
Vue异步组件实现懒加载
方法如下:component:resolve=>(require(['需要加载的路由的地址']),resolve)
import Vue from 'vue'
import Router from 'vue-router'
/* 此处省去之前导入的HelloWorld模块 */
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: resolve=>(require(["@/components/HelloWorld"],resolve))
}
]
})
ES 提出的import方法,(最常用)
方法如下:const HelloWorld = () => import('需要加载的模块地址');
(不加{ },表示直接return)
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const HelloWorld = ()=>import("@/components/HelloWorld")
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
/*component: import("@/components/HelloWorld")*/
component:HelloWorld
}
]
})
AMD写法
const helloWorld = resolve => require(['@/components/HelloWorld.vue'],resolve );
const router = new Router({undefined
routes: [
{
name: 'HelloWorld'
path: '/helloWorld',
/* component: resolve => require(['@/components/HelloWorld.vue'],resolve ) */
component: helloWorld
}
]
})
组件懒加载
原来组件中写法
<template>
<div class="hello">
<One-com></One-com>
1111
</div>
</template>
<script>
import One from './one'
export default {
components:{
"One-com":One
},
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
const方法
<template>
<div class="hello">
<One-com></One-com>
1111
</div>
</template>
<script>
const One = ()=>import("./one");
export default {
components:{
"One-com":One
},
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
异步方法
<template>
<div class="hello">
<One-com></One-com>
1111
</div>
</template>
<script>
export default {
components:{
"One-com":resolve=>(['./one'],resolve)
},
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
总结:
路由和组件的常用两种懒加载方式:
1、vue异步组件实现路由懒加载
component:resolve=>(['需要加载的路由的地址',resolve])
2、ES提出的import**(推荐使用这种方式)**
const HelloWorld = ()=>import('需要加载的模块地址')