vue路由懒加载怎样实现
Vue路由的懒加载可以通过使用`import()`函数来实现。在定义路由时,可以将组件的引入部份放在`import()`函数中,以下所示:
```javascript
const Foo = () => import('./Foo.vue')
const Bar = () => import('./Bar.vue')
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
```
使用`import()`函数引入的组件会被打包成独立的文件,并在页面需要时进行异步加载,以减少初始加载时间。注意,使用`import()`函数引入的组件需要使用箭头函数的方式定义。
另外,如果使用Vue CLI创建项目,可以通过配置`webpack`的`code splitting`来自动实现懒加载。在`vue.config.js`中添加以下配置:
```javascript
module.exports = {
// ...
chainWebpack: config => {
config.plugins.delete('prefetch')
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.compilerOptions = {
...options.compilerOptions,
isCustomElement: tag => /^ion-/.test(tag)
}
return options
})
}
}
```
这样,在定义路由时,可以直接依照普通方式引入组件,以下所示:
```javascript
import Foo from './Foo.vue'
import Bar from './Bar.vue'
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
```
Vue CLI会自动将这些组件进行懒加载处理。
TOP