uniapp中vue3版在setup父级组件调用子组件方法详解

组件是前端开发中重要的组成部分,组件的存在不仅在开发前期节约大量的开发时间、提高效率,在项目后期维护中通过组件能更加便捷的批量优化或改版特定样式及效果。

既然组件对于前端开发者有如此大的优势,那么在uniapp开发语法糖setup模式下,要如何在父组件中实现调用子组件的方法呢?

本篇文章就给出详细的代码及说明,一步一步的告诉你如何调用子组件方法。

一、创建子组件childmodel   

    在components中创建子组件childmodel.vue,案例内容如下

<template>
<view class="">子组件内容展示</view>
</template>
<script setup>
const testFun = () => {
console.log("这是子组件方法testFun")
}
// 暴露方法给父级
defineExpose({
testFun
});
</script>
二、父级调用子组件方法testFun

    在父级引入组件childmodel后,添加点击事件调用子组件方法testFun()

<template>
<view class="">
<childmodel ref="childRef"></childmodel>
<view @click="clickChild" class="" style="background-color: #f00;color: #fff;height: 90rpx;line-height: 90rpx;text-align: center;">
点击测试
</view>
</view>
</template>
<script setup>
import { ref } from 'vue';
import childmodel from"./childmodel.vue"
const childRef = ref(null);
const clickChild = () => {
childRef.value?.testFun();
}
</script>
三、代码要点

    1、子组件方法需要在defineExpose中暴露出来

    2、父级需要引入子组件

    3、需要给组件定义ref

    4、ref名称和js变量名必须一致

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!