Vuejs lazy loading routes in webpack template

送分小仙女□ 提交于 2019-12-24 20:24:01

问题


I have created vuejs project with vue-cli tools and webpack template.

vue init webpack my-project

I don't know how to implement lazy loading on routes with templates

currently i have two routes in router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Test from '@/components/Test'

Vue.use(Router)

export default new Router({
   mode: 'history',
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/test',
      name: 'test',
      component: Test
    }
  ]
})

And its imported in main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

But it doesn't contain the lazy loading implementation how can i do it??


回答1:


instead of using

import Test from '@/components/Test'

use as

const Test = () => import('@/components/Test');

lazy loading Documentataion




回答2:


Nice way to do this:

function load (component) {
  return () => import(`@/${component}.vue`)
}

...
routes: [
    { path: '/', component: load('Hello') },


来源:https://stackoverflow.com/questions/48440794/vuejs-lazy-loading-routes-in-webpack-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!