首页 > 解决方案 > 如何使用 ts 在 vue3 的渲染函数中公开组件方法

问题描述

我想在父文件中调用子组件方法,子组件由渲染函数创建。下面是我的代码

child.ts


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

    const getCropper = () => {
      return cropper
    }

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

父.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>

标签: typescriptvue.jsvue-componentvuejs3vue-render-function

解决方案


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

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

推荐阅读