3

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

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>
4

2 回答 2

3

组件实例可以通过 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()
于 2021-06-07T06:57:40.313 回答
0

另一种方法是:

child.ts

import { getCurrentInstance } from 'vue';

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

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

孩子.d.ts

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

父.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>
于 2022-01-28T09:20:55.977 回答