Composition-api: shall we support defineAsyncComponent like vue3?or we have another way to support async component

Created on 7 Feb 2021  路  5Comments  路  Source: nuxt-community/composition-api

馃啋 Your use case
want to use async component

馃啎 The solution you'd like

like defineAsyncComponent
https://github.com/vuejs/rfcs/pull/148

enhancement

Most helpful comment

just found https://vuejs.org/v2/guide/components-dynamic-async.html

I think a complete wrapper would be

function defineAsyncComponent(options) {
   const component = options.loader()
   return {
      component,
      loading: options.loadingComponent,
      error: options.errorComponent,
      delay: options.delay,
      timeout: options.timeout
   }
}

I will create a issue (and maybe a PR) in vue/composition-api tomorow

All 5 comments

You can just write your own wrapper for this (this is also a vue thing and not a nuxt thing so I hope there are some packages out there that implement that for vue2)

For this

import { defineAsyncComponent } from "vue"

// with some  options
const AsyncFooWithOptions = defineAsyncComponent({
  loader: () => import("./Foo.vue"),
  loadingComponent: LoadingComponent,
  errorComponent: ErrorComponent
})

you can write something like this (not shure how events, props work out of the box but you get the idea...) - this is not tested and my contain bugs:

import { defineComponent, ref } from "vue"

function defineAsyncComponent({loader, loadingComponent, errorComponent}) {
   return defineComponent({
      setup() {
          const status = ref(0)
          const cmp = ref(null)
          const load = loader()

          load.then(() => status.value = 1)
          load.catch(() => status.value = -1)

          return { status, cmp }
      },
      render(h) {
        if( status.value === 0) return h(loadingComponent)
        else if( status.value === 1) return h(this.cmp.value)
        else return h(errorComponent)
      }
  })  
}

@JanusSpark Very interesting suggestion, but I agree with @mathe42 that this is a matter for upstream Vue Composition API - do raise there.

They might be open to a PR as it is not a principled decision not to have this helper: see https://github.com/vuejs/composition-api/pull/390#issuecomment-647488094

just found https://vuejs.org/v2/guide/components-dynamic-async.html

I think a complete wrapper would be

function defineAsyncComponent(options) {
   const component = options.loader()
   return {
      component,
      loading: options.loadingComponent,
      error: options.errorComponent,
      delay: options.delay,
      timeout: options.timeout
   }
}

I will create a issue (and maybe a PR) in vue/composition-api tomorow

Just got merged.

Was this page helpful?
0 / 5 - 0 ratings