vue 路由(vue-router)懒加载的实现

1.要实现路由懒加载必须的先安装插件

1. npm i babel-plugin-syntax-dynamic-import -D

2..bablerc 中引入 syntax-dynamic-import 插件
{
     
	"presets": ["env"],
	"plugins": ["syntax-dynamic-import"]
}

2.路由实现方式

2.1 未用懒加载

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
        }
      ]
    })

2.2 实现懒加载

2.2.1 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:HelloWorld
    }
  ]
})

简写为:如下:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export const otherRouter ={
     
  routes: [
    {
     
      path: '/',
      name: 'HelloWorld',
      component: () => import("@/components/HelloWorld")
    }
  ]
}

2.2.2 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))
    }
  ]
})

3.路由嵌套

export const otherRouter = {
     
	path: '/',
	name: 'otherRouter',
	redirect: '/login',
	component: Main,
	children: [{
     
			path: 'home',
			title: {
     
				i18n: 'home'
			},
			name: 'home_index',
			component: () => import('@/views/home/home.vue')
		},
		{
     
			path: 'priceTag',
			title: {
     
				i18n: 'priceTag'
			},
			name: 'priceTag',
			component: () => import('@/views/bsm/priceTag/priceTag.vue')
		}, 
	]
};

你可能感兴趣的:(前端框架搭建,vue-router,前端开发遇到的问题,vue,plugin)