typescript - 如何使用 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>
解决方案
组件实例可以通过 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()
推荐阅读
- angular - Angular 材质 UI 网格结构
- reactjs - 可以在 next-i18next 中使用 redux store 作为翻译资源吗?
- python - Python:如何列出与文件夹名称列表匹配的子目录?
- oracle - Oracle Text 将单词截断为 64 个字符,但令牌限制为 64 个字节
- reactjs - 在 React JS 中清除屏幕上可见数字的问题
- flutter - Flutter:“位置参数太多:预期为 0,但找到了 1”
- reactjs - 在 React 应用程序中嵌入 mongo 图表的锄头
- git - 使用 git branch 有不同的路径?
- bash - stderr 重定向的奇怪行为
- python - 在编辑照片时,如何在 python 中为照片添加元数据?