Skip to content

Instantly share code, notes, and snippets.

@ffxsam
Last active May 22, 2024 17:48
Show Gist options
  • Save ffxsam/b7f415969c9529279ec35e95e5ffd7af to your computer and use it in GitHub Desktop.
Save ffxsam/b7f415969c9529279ec35e95e5ffd7af to your computer and use it in GitHub Desktop.
Vue 3's Suspense component, ready for use in Vue 2.x (TypeScript)
import Vue from 'vue';
export const Suspense = Vue.extend({
name: 'Suspense',
data: () => ({
resolved: false,
}),
async created() {
const setupMethod = (this.$parent as any).setup;
if (!setupMethod) {
throw new Error(
'[Suspense] No setup method found - make sure Suspense is at root ' +
'level, just inside <template>'
);
}
await setupMethod();
this.resolved = true;
},
render(createElement) {
return createElement(
'div',
this.resolved ? this.$slots.default : this.$slots.fallback
);
},
});
@Sjoerd82
Copy link

How to apply this in real-life? I've added this to my main.ts. I had to add to register the component, so I had to change it to:

let suspense = Vue.extend({
  name: 'Suspense',
  data: () => ({
    resolved: false,
  }),
  async created() {
    const setupMethod = (this.$parent as any).setup;
    if (!setupMethod) return;

    await setupMethod();
    this.resolved = true;
  },
  render(createElement) {
    return createElement(
      'div',
      this.resolved ? this.$slots.default : this.$slots.fallback,
    );
  },
});
// register
Vue.component('Suspense', suspense)

Then I went ahead and created an async setup()-component, and wrapped it in a -tag.

<Suspense>
    <AsyncComponent/>
    <template #fallback>Loading...</template>
</Suspense>

Which contains something like:

export default {
    async setup() {
        let thing = await someAsyncFunction()
    }
}

However, it remains stuck in fallback, because the setup()-function doesn't seem to exist in this.$parent. I've been going through "this", but cannot find the component/setup-function anywhere in here. I think you have a different usecase in mind perhaps (perhaps not globally?)?

@ffxsam
Copy link
Author

ffxsam commented Sep 18, 2022

setup() needs to be a method:

method: {
  async setup() { }
}

@carvaofficial
Copy link

Hi!! I´m sorry, but this component isn't working correctly. It doesn't have async reactivity to the setup() method. Also it doesn't work on Nuxt 2.X

@ffxsam
Copy link
Author

ffxsam commented May 22, 2024

@carvaofficial You shouldn't need this anymore. I'll go ahead and delete this gist soon.

@carvaofficial
Copy link

But... Can I use native Suspense from Vue 3 un Vue 2.X??

@ffxsam
Copy link
Author

ffxsam commented May 22, 2024

I can't really offer any guidance in getting this to work in Nuxt. If you follow the instructions above (and declare a setup() method), it should work ok in a standard Vue 2 application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment