我不能在Vue3中调用父组件中的子组件方法
在Vue2中,我可以像这样调用子组件方法
this.$root.$refs.ChildComponent.methodName()但是在Vue3中,我收到这样一个错误
runtime-core.esm-bundler.js:218 Uncaught TypeError: Cannot read properties of undefined (reading 'methodName')发布于 2022-09-15 05:18:43
您可能希望将一个道具传递给子对象,并通过调用该方法来对更改事件作出反应。这可能是这样的:
<!-- Parent.vue -->
<script setup>
/* declare invokeChildMethod */
</script>
<template>
<Child :prop="invokeChildMethod" />
</template>从下面的代码中可以看到,当变量(此处称为invokeChildMethod)发生变化(在父变量中)时,将触发子变量的事件。
发布于 2022-09-15 12:06:39
defineExpose可以施展魔法。你可以这样做:
// in Parent
<template>
<ChildComponent ref="myChild"/>
</template>
<script>
const myChild = ref(null);
function() {
myChild.childMethod();
}
</script>// ChildComponent
<template> ... </template>
<script setup>
function childMethod() {
// do something
}
defineExpose({
childMethod
});
</script>https://stackoverflow.com/questions/73725505
复制相似问题