父组件调用子组件中的方法,这是个看似不常见,但是大家都会遇到的问题。在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
未定义,这时直接引入它便好。