Vue实现路由懒加载

Vue路由懒加载

这是个大部分Vue搭建的项目常用的写法
可以提高Vue首屏加载的速度
虽然已经学会,但是还是想记录一下
避免以后可能少用Vue的时候我还能在这里温故知新

import Vue from 'vue'
import Router from 'vue-router'
import login from '@/view/login/login' // 正常的import引入
import error from '@/view/error.vue'
import error2 from '@/view/error2.vue'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: login // 正常的import引入
    },
    {
      path: '/error',
      name: 'error',
      component: resolve => require(['@/view/error'], resolve) // 懒加载的写法,需要路由跳转才加载
    },
    {
      path: '/error2',
      name: 'error2',
      component: resolve => require(['@/view/error2'], resolve)
    },
    {
      path: '/',
      component: resolve => require(['@/view/index/index'], resolve),
      children: [
        {
          path: '/',
          name: 'index',
          component: resolve => require(['@/components/map/map'], resolve)
        },```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VueRouter 路由懒加载可以通过动态导入的方式实现,即在路由定义时通过 import() 函数异步加载组件。这样当用户访问该路由时,组件才会被加载,从而减少了首次加载时的文件大小和加载时间,提高了页面加载速度。 具体实现步骤如下: 1. 在路由定义时,将组件定义为一个函数,该函数通过 import() 函数动态加载组件。 ```js const router = new VueRouter({ routes: [ { path: '/about', component: () => import('./views/About.vue') } ] }) ``` 2. 在 webpack 中配置 babel-plugin-syntax-dynamic-import 插件,以支持 import() 函数动态导入语法。 ```js // webpack.config.js module.exports = { // ... module: { rules: [ // ... { test: /\.js$/, loader: 'babel-loader', options: { plugins: ['syntax-dynamic-import'] } } ] } } ``` 3. 在生产环境中开启路由懒加载,可以通过 webpack 的 SplitChunksPlugin 插件将路由组件打包成单独的文件,从而实现按需加载。 ```js // webpack.config.js const path = require('path') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') module.exports = { mode: 'production', entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[contenthash].js', chunkFilename: '[name].[contenthash].js' }, module: { rules: [ // ... ] }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './public/index.html' }), new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' }) ], optimization: { splitChunks: { chunks: 'all' } } } ``` 这样就可以实现 VueRouter 路由懒加载了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值