Vue路由组件的按需加载方法总结

1. 普通加载

在使用vue-cli构建项目后,我们通常会在Router文件夹下的index.js中引入相关的路由组件。例如:

import Hello from '@/components/Hello'
import Boy from '@/components/Boy'
import Girl from '@/components/Girl'

这种方式会导致Webpack在执行npm run build时,将所有内容打包成一个大的JS文件。如果页面较多,会导致文件体积过大,加载缓慢。

2. 异步按需加载

为了优化加载速度,可以将JS文件拆分成多个小文件,并实现按需加载(仅在需要时加载)。这种方法使用 import() 动态导入来实现,例如:

const Hello = () => import('@/components/Hello')
const Boy = () => import('@/components/Boy')
const Girl = () => import('@/components/Girl')

这样处理后,每个页面会被独立打包,只有在需要时才会加载相应的文件,显著提升了加载性能。

pdf 文件大小:49.59KB