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>
相关推荐
PedroQue991 天前
V1.6.1性能优化:高频路径提速与代码精简
前端·uni-app
猩猩程序员1 天前
将 LiteLLM 迁移到 Rust —— 构建最快、最轻量的 AI Gateway
前端
lichenyang4531 天前
JSBridge 分发升级:为什么要从 if-else 变成 Registry > 这是「ASCF 架构升级」系列的第 3 篇
前端
码上天下1 天前
流式响应断了,前端怎么自动重连续传
前端
anyup1 天前
来简单聊聊鸿蒙开发,万元奖金的事~
前端·华为·harmonyos
北凉温华1 天前
Univer 在线表格模块使用说明
前端
lichenyang4531 天前
WebRuntimePage 拆分:从大页面到运行时控制器
前端
竹林8181 天前
从报错到跑通:我用 @solana/web3.js 开发 Solana 钱包连接踩过的三个坑
前端
MariaH1 天前
Node中操作MySQL
前端
还有多久拿退休金1 天前
一个 var 让整个团队加班到凌晨——JS 闭包的那些暗坑
前端·javascript