简体   繁体   English

如何使用 ts 在 vue3 中渲染 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.我想在父文件中调用子组件方法,子组件是通过渲染 function 创建的。 below is my code下面是我的代码

child.ts child.ts


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

    const getCropper = () => {
      return cropper
    }

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

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

Component instance can be extended by using expose , this is useful for cases where setup return value is already render function:组件实例可以通过使用来扩展,这对于setup返回值已经呈现expose的情况很有用:

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, eg:通过expose的实例是类型不安全的,需要手动输入,例如:

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

child.value?.getCropper()

Another mean to do it:另一种方法是:

child.ts 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孩子.d.ts

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM