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>
相关推荐
知心宝贝12 分钟前
写了那么久的前端,你真的了解浏览器背后的“小动作“吗?
前端·程序员·浏览器
wycode12 分钟前
Vue2实践(2)之用component做一个动态表单(一)
前端·javascript·vue.js
维李设论14 分钟前
前端智能化 | AG-UI实践及原理浅析
前端·aigc·agent
第七种黄昏14 分钟前
Vue3 中的 ref、模板引用和 defineExpose 详解
前端·javascript·vue.js
一只卡比兽15 分钟前
动态规划与贪心算法详解:原理、对比与代码实践
前端
aiwery18 分钟前
一文掌握 TypeScript 工具类型:Record、Partial、Omit、Pick 等实战用法
前端·代码规范
ankleless32 分钟前
C语言(12)——进阶函数
前端·html
一条上岸小咸鱼36 分钟前
Kotlin 基本数据类型(四):String
android·前端·kotlin
我是哈哈hh1 小时前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js
张元清1 小时前
电商 Feeds 流缓存策略:Temu vs 拼多多的技术选择
前端·javascript·面试