子组件调用方法 - 组合 API

Der*_*ima 23 javascript vue.js vuejs3 vue-composition-api vue-script-setup

我有一个父组件,我需要调用其子组件之一中存在的方法:

<template>
  <div>
    <button @click="callChildMethod">
    <child-component ref="child" />
  </div>
</template>
<script>
  setup(props) {
    const child = ref(null)
    const callChildMethod = () => {
      child.doSomething()
    }

    return {
      child,
      callChildMethod
    }
  }
</script>
  
Run Code Online (Sandbox Code Playgroud)

子组件包含doSomething方法:

const doSomething = () => { console.log('calling method....') }
Run Code Online (Sandbox Code Playgroud)

由于我使用的是 VueJS3 和 Composition API,因此我的方法是使用模板引用来调用子组件中的方法。显然不起作用,但我看不出我错过了什么。有人对这个有线索吗?提前致谢

Анд*_*ока 58

PS <script setup>(Composition API)需要使用defineExpose

https://v3.vuejs.org/api/sfc-script-setup.html#defineexpose

父组件:

<script setup>
...
const childred = ref();

childred.value.doSomething()
</script>

<template>
  <ChildrenComponent ref="childred" />
</template>

Run Code Online (Sandbox Code Playgroud)

儿童组件:

<script setup>
...
function doSomething(){
  console.log(1);
}

defineExpose({
  doSomething,
});

</script>

<template>
  <div>123</div>
</template>

Run Code Online (Sandbox Code Playgroud)


Bou*_*him 17

您缺少 中的值字段ref,它应该是:

 const callChildMethod = () = {
  child.value.doSomething()
}
Run Code Online (Sandbox Code Playgroud)

编辑 Amazing-cori-5hgi9

如果子组件是使用脚本设置语法定义的,则应该使用defineExpose将该方法公开给外部

 const callChildMethod = () = {
  child.value.doSomething()
}
Run Code Online (Sandbox Code Playgroud)

家长:

<script setup>

function doSomething(){
  //......
}

defineExpose({
  doSomething,
});

</script>
Run Code Online (Sandbox Code Playgroud)

或者

<template>
  <div>
    <button @click="callChildMethod">
    <child-component ref="child" />
  </div>
</template>
<script>
  setup(props) {
    const child = ref(null)
    const callChildMethod = () => {
      child.doSomething()
    }

    return {
      child,
      callChildMethod
    }
  }
</scrip>
Run Code Online (Sandbox Code Playgroud)