[英]how to expose component methods in render function in vue3 with ts
我想在父文件中調用子組件方法,子組件是通過渲染 function 創建的。 下面是我的代碼
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>
組件實例可以通過使用來擴展,這對於setup
返回值已經呈現expose
的情況很有用:
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
}
}
孩子.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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.