JavaScript/vue.js/defineAsyncComponent

来自康健生活

标题文本

Async Components

import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent({
  loader: () => import('./foo.vue'),
  loadingComponent: LoadingComponent,
  errorComponent: ErrorComponent,
  delay: 200,
  timeout: 3000,
  suspensible: false,
  /**
   *
   * @param {*} error 错误信息对象
   * @param {*} retry 一个函数,用于指示当 promise 加载器 reject 时,加载器是否应该重试
   * @param {*} fail  一个函数,指示加载程序结束退出
   * @param {*} attempts 允许的最大重试次数
   */
  onError(error, retry, fail, attempts) {
    if (error.message.match(/fetch/) && attempts <= 3) {
      // 请求发生错误时重试,最多可尝试 3 次
      retry()
    } else {
      fail()
    }
  }
})

异步

defineAsyncComponent 函数允许使用 async/await 处理异步问题。

useage

通常意义上只能加载 vue 后缀格式的文件。也有高分的实现 vue3-sfc-loader

定义异步组件

const AsyncComp = defineAsyncComponent(() => {
  // 加载函数返回Promise
  return new Promise((resolve, reject) => {
    fetch('http://uri/')
      .then(response => response.text())
      .then((_) => {
        // ...可以从服务器加载组件
        resolve(/* loaded component */)
      })
  })
})

ES 模块动态导入

const AsyncComp = defineAsyncComponent(() =>
  import('./components/MyComponent.vue')
)

理论上也支持远程文件。

defineAsyncComponent(async () => (await import('http://example.com/path/to/foo.vue')).default)

打包

vite

将需要的 vue 组件通过 rollup 单独打包为 es 或 umd 格式。

vite.config.ts
// https://vitejs.dev/config/
export default defineConfig({
// ...
  build: {
    lib: {/*... */},
    rollupOptions: {
      input: {
        // eq:
        select: path.resolve(__dirname, 'packages/select/index.vue'),
        // ...
      },
// ...
})

在使用时直接引入。

const Select = defineAsyncComponent(async () => await import(/* selecct component by es url*/))

package.json

// ... "main": "./bundle/linking-kwy.cjs.js", "module": "./bundle/linking-kwy.es.js", "exports": { ".": { "import": "./bundle/linking-kwy.es.js", "require": "./bundle/linking-kwy.cjs.js" } },

// ...

CSS

在打包过程中可以通过组件 vite-plugin-css-injected-by-js 将 CSS 合并入 JS 文件中,使用起来也很简单

// https://www.npmjs.com/package/vite-plugin-css-injected-by-js
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'
// ...
  plugins: [
    cssInjectedByJsPlugin(),
// ...
Insert comment here

注册

pinia

引入的组件通过注册进而实现全局使用,这里找到一个实例。以供参考。

import { markRaw, defineAsyncComponent } from 'vue'
import { defineStore } from 'pinia'

export const dynamicComponentsStoreId = 'dynamicComponents'

export const useDynamicComponentsStore = defineStore(dynamicComponentsStoreId, {
  state: () => ({
    dynamicComponents: new Map<string, any>(),
  }),
  actions: {
    registerComponent(type: string, component: any) {
      this.dynamicComponents.set(type, component)
    },
    getComponent(type: string) {
      return this.dynamicComponents.get(type)
    },
  },
})

dynamicComponentsStore.registerComponent(
  'CustomComponent',
  markRaw(
    defineAsyncComponent(
      () => import(`./components/CustomComponent/CustomComponent.vue`)
    )
  )
)

(来源摘自互联网示例,作者 https://stackoverflow.com/a/77637766)

other

在思考远程组件加载这个方案的时候,Vue 加载远程组件的解决方案 这篇文章给与我极大的帮助。在当今中国普遍 CTRL C 和 CRTL V 复制粘贴垃圾文的现象下,仍有愿意思考并实践的博主真的不多了。点赞。

在此方案下我的一个成功实现

const AsyncFwdSearchCardTop = defineAsyncComponent({
  loader: async () => {
    console.log('Loading component...')
    const module = await import('https://www.unpkg.com/linking-kwy@0.0.8/bundle/linking-kwy.es.js')
    return module.default.Linking
  },
// ...
})