Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active December 4, 2020 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/6091f26558ffe1f9dd570c8996e394a1 to your computer and use it in GitHub Desktop.
Save james2doyle/6091f26558ffe1f9dd570c8996e394a1 to your computer and use it in GitHub Desktop.
An example of how to use async data within a Vue component
/**
* We need to use a plain JS (or TS) file in order to handle all the async
* code we are going to handle
* we also need to follow the Async Component Guide:
* @see https://vuejs.org/v2/guide/components-dynamic-async.html#Handling-Loading-State
*/
// some API call, async task, or delayed function
const myAsyncFunction = () =>
new Promise((resolve) => {
setTimeout(
() => resolve(() => ({ msg: 'After 2 seconds, I appeared!' })),
2000
);
});
// we use a functional component to make sure it renders ASAP
const LoaderComponent = {
functional: true,
render: (createElement) =>
createElement('div', {
class: {
loading: true
},
domProps: {
innerHTML: 'Loading...'
}
})
};
const ErrorComponent = {
functional: true,
render: (createElement) =>
createElement('div', {
class: {
error: true
},
domProps: {
innerHTML: 'Error!'
}
})
};
export default () => ({
// The component to load (should be a Promise)
component: myAsyncFunction().then((data) => {
return {
name: 'AsyncVueComponent',
template: `<div class="async-vue-component"><div v-text="msg"></div></div>`,
data
};
}),
// A component to use while the async component is loading
loading: LoaderComponent,
// A component to use if the load fails
error: ErrorComponent,
// The error component will be displayed if a timeout is
// provided and exceeded. Default: Infinity.
timeout: 3000
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment