vue3 vite异步组件及路由懒加载

1 篇文章 0 订阅

一、前言

  • 异步组件声明方法的改变:Vue 3.x 新增一个辅助函数defineAsyncComponent,用来显示声明异步组件
  • 异步组件高级声明方法中的 component 选项更名为loader
  • loader绑定的组件加载函数不再接收resolve和reject参数,而且必须返回一个Promise

二、Vue 2.x与Vue 3.x定义比较

2-1.异步组件/路由定义比较

  • 2-1-1.在 Vue 2.x 中,声明一个异步组件只需这样:
const asyncPage = () => import('./views/home.vue')
  • 2-1-2.在 Vue 3.x 中,异步组件的导入需要使用辅助函数defineAsyncComponent来进行显式声明。如下:
<template>
  <div>
    <h1>Async Components</h1>
    <p>异步组件测试</p>
    <child />
  </div>
</template>
<script>
import { defineAsyncComponent } from 'vue'
const child = defineAsyncComponent(() => import('@/components/async-component-child.vue'))
export default {
  name: 'async-components',
  components:{
    'child': child
  }
};
</script>

2-2.声明方式比较

  • 2-2-1.Vue 2.x中异步组件的声明有更高级的声明方式。如下:
const asyncPageWithOptions  = {
  component: () => import('./views/home.vue'),
  delay: 200,
  timeout: 3000,
  error: ErrorComponent,
  loading: LoadingComponent
}

所以,下面的异步组件声明:

const asyncPage = () => import('./views/home.vue')

等价于:

const asyncPageWithOptions  = {
  component: () => import('./views/home.vue')
}
  • 2-2-2.Vue 3.x中也可以这样声明异步组件。只是其中的component需要改为loader。如下:
const asyncPageWithOptions  = defineAsyncComponent({
  loader: () => import('./views/home.vue'),
  delay: 200,
  timeout: 3000,
  error: ErrorComponent,
  loading: LoadingComponent
})

2-3.异步组件加载函数返回比较

  • 2-3-1.在Vue 2.x中接收resolve和reject
// 2.x version
const oldAsyncComponent = (resolve, reject) => {
  /* ... */
}

  • 2-3-2.在Vue 3.x中始终返回Promise:
// 3.x version
const asyncComponent = defineAsyncComponent(
  () => new Promise((resolve, reject) => {
      /* ... */
  })
)

Vue 3.x的异步组件加载函数将不再接收resolve和reject,而且必须始终返回Promise。也就是说,工厂函数接收 resolve 回调的方式定义异步组件在 Vue 3.x 不能使用了。

// 在 Vue 3.x 中不适用
export default {
  components: {
    asyncPage: resolve => require(['@/components/list.vue'], resolve)
  },
}

三、Vue3实践

提示: 如果是用vite工具来构建项目,在本地开发使用import做路由懒加载,可以正常加载,但是会报警告;打包到生产环境会报错,页面不会正常展示,可以使用以下两种方法来实现。

3-1.路由懒加载实现

  • 3-1-1.defineAsyncComponent方法
// router/index.js
import { defineAsyncComponent } from 'vue'
const _import = (path) => defineAsyncComponent(() => import(`../views/${path}.vue`));
const routes = [
  {
    path: '/async-component',
    name: 'asyncComponent',
    component: _import('home'),
  }
];

  • 3-1-2.import.meta.glob方法
// 1.上面的方法相当于一次性加载了 views 目录下的所有.vue文件,返回一个对象
const modules = import.meta.glob('../views/*/*.vue');
const modules ={
    "../views/about/index.vue": () => import("./src/views/about/index.vue")
}
// 2.动态导入的时候直接,引用
const router = createRouter({
  history: createWebHistory(),
  routes: [
    // ...
    {
      path: 'xxxx',
      name: 'xxxxx',
      // 原来的方式,这个在开发中可行,但是生产中不行
      // component: () => import(`../views${menu.file}`),
      // 改成下面这样
      component: modules[`../views${filename}`]
    }
    // ...          
  ],
})

3-2.异步组件实现

<template>
  <div>
    <h1>Async Components</h1>
    <p>异步组件测试</p>
    <child></child>
  </div>
</template>
<script>
import { defineAsyncComponent } from 'vue'
const child = defineAsyncComponent(() => import('@/components/async-component-child.vue'))
export default {
  name: 'async-components',
  components:{
    'child': child
  }
};
</script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ViteVue 中,你可以使用路由懒加载来优化你的应用的性能。下面是一个简单的示例来演示如何在 Vite 中使用 Vue 路由懒加载: 首先,确保你已经安装了 `vue-router` 和 `@vue/compiler-sfc`,你可以使用以下命令进行安装: ``` npm install vue-router @vue/compiler-sfc ``` 接下来,在你的项目中创建一个路由文件,比如 `router.js`,并编写你的路由配置。在配置路由时,可以使用 `import` 语法来实现懒加载。 ```javascript import { createRouter, createWebHistory } from 'vue-router' const routes = [ { path: '/', name: 'Home', component: () => import('./views/Home.vue') // 使用懒加载 }, { path: '/about', name: 'About', component: () => import('./views/About.vue') // 使用懒加载 } ] const router = createRouter({ history: createWebHistory(), routes }) export default router ``` 在上面的代码中,`import()` 函数用于异步加载组件。这样,当用户访问某个路由时,对应的组件将会被动态加载并渲染。 最后,在你的主入口文件(比如 `main.js`)中导入路由,并将其挂载到 Vue 实例上。 ```javascript import { createApp } from 'vue' import App from './App.vue' import router from './router' createApp(App) .use(router) .mount('#app') ``` 现在,你已经成功地在 Vite 中配置了 Vue 路由懒加载。每次用户访问特定的路由时,相关的组件将会按需加载,从而提高了应用的性能和加载速度。 希望对你有帮助!如果你还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值