如何使用 ts 在 vue3 中的渲染函数中公开组件方法

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

我想调用父文件中的子组件方法,子组件是通过render函数创建的。 下面是我的代码

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>

可以使用 expose 扩展组件实例,这对于 setup return 值已经是渲染函数的情况很有用:

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

expose暴露的实例类型不安全,需要手动输入,例如:

const child = ref<ComponentPublicInstance<{}, ChildPublicInstance>>();

child.value?.getCropper()

另一种做法:

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>