Vue3 父组件调用子组件方法

Kha*_*ang 11 vuejs3

Vue3无法在父组件中调用子组件方法

在Vue2中,我可以像这样调用子组件方法

this.$root.$refs.ChildComponent.methodName()
Run Code Online (Sandbox Code Playgroud)

但是在Vue3中,我收到这样的错误

runtime-core.esm-bundler.js:218 Uncaught TypeError: Cannot read properties of undefined (reading 'methodName')
Run Code Online (Sandbox Code Playgroud)

小智 18

defineExpose可以发挥魔法。你可以这样做:

家长

<template>
  <ChildComponent ref="myChild"/>
</template>

<script>
const myChild = ref(null);

function() {
  myChild.value.childMethod();
}
</script>
Run Code Online (Sandbox Code Playgroud)

子组件

<template>
  ...
</template>

<script setup>
function childMethod() {
 // do something
}    

defineExpose({
  childMethod
});
</script>
Run Code Online (Sandbox Code Playgroud)


cor*_*eam 10

DefineExpose 可以公开子组件的 props 和方法

// in Parent
<template>
<ChildComponent ref="myChild"/>
</template>

<script setup>
const myChild = ref(null);

function testCall() {
  myChild.value.childMethod();
}

</script>
Run Code Online (Sandbox Code Playgroud)
// ChildComponent
<template> ... </template>
<script setup>

function childMethod() {
 // do something
}    

defineExpose({
        childMethod
    });
</script>
Run Code Online (Sandbox Code Playgroud)


STh*_*STh 0

您可能希望将 prop 传递给子级,并通过调用该方法对更改事件做出反应。这可能看起来像这样:

<!-- Parent.vue -->
<script setup>
/* declare invokeChildMethod */
</script>

<template>
  <Child :prop="invokeChildMethod" /> 
</template>
Run Code Online (Sandbox Code Playgroud)

从下面的代码中可以看出,当变量(此处称为invokeChildMethod)更改(在父级中)时,将触发子级的事件。

这是有关在 Vue3 中观看道具的资源