uniapp中父组件调用子组件方法

实现过程(setup语法糖形式下)

  1. 在子组件完成方法逻辑,并封装。
  2. 在子组件中使用defineExpose暴露子组件的该方法。
  3. 在父组件完成子组件ref的绑定。
  4. 通过ref调用子组件暴露的方法。

子组件示例

html 复制代码
<template>
</template>

<script setup>
import { defineEmits } from 'vue';

// 方法的定义
const contentIsEmpty = () => {
    uni.showModal({
        title: `请先完成"${props.name}"的输入`,
        showCancel: false
    })
}

// 暴露方法
defineExpose({
    contentIsEmpty
})
</script>

<style lang="scss" scoped>
</style>

父组件示例

html 复制代码
<template>
    <!-- 绑定ref -->
    <ContentInput name="xxx" ref="contentInputRef"/>
</template>

<script setup>
    // 导入组件
    import ContentInput from '@/components/content/content.vue';

    // 定义ref
    const contentInputRef = ref(null)

    // 调用子组件所暴露的方法
    contentInputRef.value.contentIsEmpty()
</script>

<style lang="scss" scoped>
</style>
相关推荐
百思可瑞教育3 分钟前
ActiveMQ、RocketMQ、RabbitMQ、Kafka 的全面对比分析
vue.js·分布式·rabbitmq·rocketmq·activemq·北京百思可瑞教育·百思可瑞教育
li35748 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj8 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel8 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel8 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
西陵10 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld10 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
东风西巷11 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求
萌萌哒草头将军11 小时前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js