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>
相关推荐
weixin_4569042711 分钟前
C# 中的回调函数
java·前端·c#
kura_tsuki25 分钟前
[Web网页] LAMP 架构与环境搭建
前端·架构
yinuo34 分钟前
UniApp+Vue3多分包引入同一 npm 库被重复打包至 vendor 的问题分析与解决
前端
码界奇点1 小时前
Spring Web MVC构建现代Java Web应用的基石
java·前端·spring·设计规范
yinuo1 小时前
UniApp + Vue3 使用 marked 报错:SyntaxError /[\p{L}\p{N}]/u 问题分析与解决
前端
大前端helloworld1 小时前
前端梳理体系从常问问题去完善-框架篇(Vue2&Vue3)
前端·javascript·面试
小墨宝2 小时前
web前端学习LangGraph
前端·学习
南囝coding2 小时前
React 19.2 重磅更新!这几个新特性终于来了
前端·react.js·preact
Dajiaonew2 小时前
Vue3 + TypeScript 一篇文章 后端变全栈
前端·javascript·typescript
广州华水科技2 小时前
GNSS与单北斗变形监测一体机在基础设施安全中的应用分析
前端