我的父组件有一个通过传递给它的引用来调用的子组件:
<child
ref="childRef"
/>
现在,我想从父组件运行子组件内部的函数,如下所示:
mounted() {
(this.$refs.childRef as any).testFunction();
}
当然,它适用于任何类型,但如何设置正确的类型来运行此函数?
如果我使用组件本身的类型:
(this.$refs.childRef as Child).testFunction();
它仍然说属性
testFunction
在类型“Vue”上不存在。
我使用Vue.js 2版本。
我的子组件:
@Component({})
export default class Child extends Mixins(CustomMixin) {
testFunction() {
console.log('test');
}
}
编辑: 我还找到了运行该函数的解决方案:
(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();
它使用方法
testFunction()
更新 Child 类型,并且它确实有效。虽然我不知道这是否是一个好方法。
您的代码看起来不错,它应该作为子组件工作
ref
仅保存子组件的实例。这是代码片段。请查看并交叉检查您的代码以找出根本原因。
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<child ref="childCom"></child>
</div>
Vue.component('child', {
methods: {
testFunction() {
console.log('test function call')
}
}
});
var app = new Vue({
el: '#app',
mounted() {
(this.$refs.childCom as Child).testFunction();
}
});
到目前为止,这是我找到的解决方案:
(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();
它有效,尽管我不知道这是否是一个干净的方法。它使用 void 方法更新 Child 类型
testFunction
。
我总是使用 setup 和 lang="ts"
我认为最好的方法是:
// child-component.vue
export interface IEtapa {
fetchEnviosContar(): Promise<void>
}
const fetchEnviosContar = async ():Promise<void>=>{
console.log("hello world")
})
defineExpose<IEtapa>({
fetchEnviosContar,
})
// parent-component.vue
import Etapas, { IEtapa } from '../components/etapas/index.vue'
const refEtapasComponent = ref<IEtapa | null>(null)
refEtapasComponent.value?.fetchEnviosContar()