typescriptvue.jsvue-componentvuejs3vue-render-function

how to expose component methods in render function in vue3 with ts


I want to call the child component methods in parent file and the child component is created by render function. below is my code

child.ts


export default {
  setup(props) {
    //...

    const getCropper = () => {
      return cropper
    }

    return () =>
      // render function
      h('div', { style: props.containerStyle }, [
      ])
  }

parent.ts

<template>
 <child-node ref="child"></child-node>
</template>

<script>
export default defineComponent({
  setup(){
    const child =ref(null)
    
    // call child method
    child.value?.getCropper()


    return { child }
  }

})
</script>

Solution

  • Component instance can be extended by using expose, this is useful for cases where setup return value is already render function:

    type ChildPublicInstance = { getCropper(): void }
      ...
      setup(props: {}, context: SetupContext) {
        ...
        const instance: ChildPublicInstance = { getCropper };
        context.expose(instance);
        return () => ...
      }
    

    The instance exposed by expose is type-unsafe and needs to be typed manually, e.g.:

    const child = ref<ComponentPublicInstance<{}, ChildPublicInstance>>();
    
    child.value?.getCropper()