关于vue2.0 vue-router的按需加载

559 阅读1分钟
  • 什么是懒加载
  1. 懒加载简单来说就是延迟加载或按需加载,即在需要的时候的时候进行加载。
  2. spa应用 :single page application (单页应用):是结合web端与app端的优点,可以把web轻便,与app端的无缝衔接优势结合起来=>
  3. 就是:第一次进入页面时会请求一个html文件,刷新清除一下,切换到其他组件,此时路径也相应变化,但是并没有新的html文件请求,页面内容却变化了。
  4. 页面跳转: js渲染
  5. 优点: 页面切换快
  6. 缺点: 首屏时间稍慢,SEO差
  • 原先代码是这样写的
import infodetail from '../views/InfoDetail.vue'; 
Vue.use(VueRouter) 
const routes = [{         
    path: '/infodetail',         
    name: 'infodetail',         
    component: infodetail     
}, ] 
const router = new VueRouter({routes }) 
export default router
  • 懒加载后代码是这样的

方案一(按需加载)

const infodetail = () => import('../views/InfoDetail.vue') 
const router = new VueRouter({ 
    routes: [ { path: '/infodetail', component: infodetail } ] 
 })

方案三

const router = new Router({ 
    routes: [ { path: '/infodetail', component: (resolve) => { // 这里是你的模块 不用import去引入了 
    require(['../views/InfoDetail.vue'], resolve) } } ] 
})

方案三

// r就是resolve 
//const infodetail = r => require.ensure([], () => r(require('../views/InfoDetail.vue')), 'infodetail'); 
//(基于webpack的require.ensure技术 实现更加不同的chunkname 合并打包为一个js文件) 
const infodetail = (resolve) => {   
    require.ensure(['../views/InfoDetail'], () => {   
    resolve(require('../views/InfoDetail'),'infodetail')   
}) 
} 
// 路由也是正常的写法 这种是官方推荐的写的 按模块划分懒加载 
const router = new Router({ 
routes: [ { 
    path: '/infodetail', 
    component: infodetail, 
} 
] 
}))