【笔记】vue3.2 父组件如何调用子组件中的方法

父组件调用子组件中的方法,这是个看似不常见,但是大家都会遇到的问题。在vue2.x中可以用this.$refs、在vue3.x中也可以给子组件一个ref,然后直接.value来操作它,但是到了vue3.2中,似乎是不行了,那是因为你忽略了一个新的语法糖defineExpose

在vue3.2中,由于使用了<script setup>,在这个标签中的变量或是方法需要你主动去暴露,不然在组件外部是无法直接获取到的。废话不多说,直接上例子。

<!-- 子组件 child.vue -->
<script setup>
const childMethod = () => {
  console.log('child method.')
}

// 主动暴露childMethod方法
defineExpose({ childMethod })
</script>
<!-- 父组件 -->
<script setup>
import { ref } from 'vue'
import child from './child.vue'

const childRef = ref()

const callChildMethod = () => {
  childRef.value.childMethod()
}
</script>

<template>
  <child ref="childRef"></child>
  <button @click="callChildMethod">call</button>
</template>

如上面的例子所示,在子组件中,我们使用defineExpose主动暴露了childMethod,所以在父组件中,就可以使用了。同样的,defineExpose是不需要引入的,但是eslint可能会检测到defineExpose未定义,这时直接引入它便好。

  • 17
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Vue 3.2 ,你可以通过使用 `ref` 和 `teleport` 来实现组件调用组件方法。下面是一个示例: 在组件,你需要使用 `ref` 来创建一个引用,并将它暴露给组件。然后,在组件,你可以通过 `teleport` 将组件方法绑定到引用上。这样,组件就可以通过引用来调用组件方法了。 下面是一个示例代码: // 组件 Child.vue <template> <div> <button @click="childMethod">组件方法</button> </div> </template> <script> import { ref, teleport } from 'vue'; export default { setup() { const childMethod = () => { console.log('组件方法调用了'); }; const childMethodRef = ref(childMethod); teleport(() => { return { childMethodRef }; }); return { childMethod }; } }; </script> 在组件,你可以通过 `$refs` 来访问组件的引用,并调用组件方法。 // 组件 Parent.vue <template> <div> <button @click="callChildMethod">调用组件方法</button> <child ref="childRef"></child> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const childRef = ref(null); const callChildMethod = () => { if (childRef.value) { childRef.value.childMethodRef(); } }; return { callChildMethod }; } }; </script> 在上面的示例,我们在组件创建了一个组件的引用 `childRef`,然后通过 `this.$refs.childRef.childMethodRef()` 调用组件方法。 注意:在 Vue 3 ,需要使用 `ref` 来创建引用,而不是像 Vue 2 那样使用 `$refs`。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值