vue-with-suspense
v1.0.0
Published
Only Vue 3 support.
Downloads
4
Maintainers
Readme
Vue Suspense - it's easy
Only Vue 3 support.
This HOC (high order component) lets you create async components without boilerplate and reduced code in template tag.
How to use:
- Install package:
npm install vue-with-suspense
- Add function to your component:
import withSuspense from 'vue-with-suspense';
- Wrap your component into HOC:
components: {
Component: withSuspense(Component, Placeholder)
}
// or wrap on export
export default withSuspense(Component)
Additional params
You can pass additional props to placeholder
withSuspense(Component, Placeholder, PlaceholderProps)
type TPlaceholderProps = Record<stirng, unknown>;
Example:
<script lang="ts">
import { defineComponent } from 'vue';
import withSuspense from 'vue-with-suspense';
import MyAsyncComponent from './components/MyASyncComponent.vue';
import PlaceholderComponent from './components/PlaceholderComponent.vue';
export default defineComponent({
name: 'App',
components: {
MyAsyncComponent: withSuspense(MyAsyncComponent, PlaceholderComponent)
}
});
</script>
<template>
<div class="main">
<my-async-component />
<div>
</template>
Inside your MyAsyncComponent you can use async operations, Suspense will wait:
// MyAsyncComponent.vue
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { MyAsyncComponentPropsInterface, MyAsyncComponentInstanceInterface, DataInterface } from './types';
export default defineComponent({
name: 'MyAsyncComponent',
async setup(props: MyAsyncComponentPropsInterface): MyAsyncComponentInstanceInterface {
const renderData = ref<DataInterface | null>(null);
const response = await fetch('https://example.com/mock-json-data');
const renderData.value = await response.json();
return {
renderData
}
}
});
</script>