shunze.chen
shunze.chen

Reputation: 359

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>

Upvotes: 8

Views: 7878

Answers (2)

Danny
Danny

Reputation: 341

Another mean to do it:

child.ts

import { getCurrentInstance } from 'vue';

setup (props, { slots, emit }) {
  const { proxy } = getCurrentInstance();

  // expose public methods
  Object.assign(proxy, {
    method1, method2,
  });
  return {
    // blabla
  }
}

child.d.ts

export interface Child {
  method1: Function;
  method2: Function;
}

parent.ts

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

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

    return { child }
  }

})
</script>

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222474

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()

Upvotes: 8

Related Questions