vue3 <script setup> 执行子组件里的方法函数

在搞自定义组件开发的时候,遇到的问题,vue2时,子组件里的方法函数,可以直接通过 this.$refs.xxx.xxxx() 来执行,但在vue3中,尤其是 <script setup> 中,是不允许这样的,由于 <script setup> 目前没啥文档,相关资料,不太好找,最后再github反馈,才找到解决方案,这个方案,很简单,实际上,就是vue2的思维,没转换过来。


自定义组件

<template>
  <div>test</div>
</template>
<script lang="ts" setup>
function testLog() {
    console.log('11')
    return '22';
}
</script>

使用自定义组件

<template>
	<div>
		<test-a ref="child"/>
		<button @click="testClick">test</button>
	</div>
</template>

<script lang="ts" setup>
import {ref} from "vue";
const child = ref<any>();

const testClick = () => {
    //child.value.testLog();
    console.log(child.value.testLog())
}
</script>

vue2的思维,这样写,是会报错的。

runtime-core.esm-bundler.js:218 Uncaught TypeError: child.value.testLog is not a function

修改为下面的,就可以了。

自定义组件(最终版)

<template>
  <div>test</div>
</template>
<script lang="ts" setup>
function testLog() {
    console.log('11')
    return '22';
}

// 暴露出去
defineExpose({
    testLog
})
</script>

意思就是,vue3的自定义组件里,方法函数等,默认是不对外的,如果需要外部调用,就需要将方法函数使用 defineExpose 暴露出去。


vue版本:3.1.4

Logo

前往低代码交流专区

更多推荐