Created
October 30, 2018 06:49
-
-
Save wonderful-panda/b7f4dab381e4f1b37e0f9877589ebf2a to your computer and use it in GitHub Desktop.
[Vue.js] Helper function to make async component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue, { VNode, CreateElement } from "vue"; | |
import { RecordPropsDefinition } from "vue/types/options"; | |
import { TsxComponent } from "vue-tsx-support"; | |
export function vueAsync<Props>(definition: { | |
props?: RecordPropsDefinition<Props>; | |
renderAsync(this: Vue & Props, h: CreateElement): Promise<VNode>; | |
loading(this: Vue & Props, h: CreateElement): VNode; | |
}): TsxComponent<Vue, Props> { | |
const { props, renderAsync, loading } = definition; | |
const ret = Vue.extend({ | |
props: props || {}, | |
data() { | |
return { | |
cache: undefined as VNode | undefined | |
}; | |
}, | |
computed: { | |
_updateChecker() { | |
this.cache = undefined; | |
this.renderAsync(this.$createElement) | |
.then(vnode => { | |
this.cache = vnode; | |
}) | |
.catch(e => { | |
// TODO | |
console.log(e); | |
}); | |
return 0; | |
} | |
}, | |
methods: { | |
renderAsync: renderAsync as (h: CreateElement) => Promise<VNode>, | |
loading: loading as (h: CreateElement) => VNode | |
}, | |
render(h): VNode { | |
this._updateChecker; | |
return this.cache || this.loading(h); | |
} | |
}); | |
return ret as any; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment