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>
相关推荐
一个游离的指针20 分钟前
ES6基础特性
前端·javascript·es6
layman052821 分钟前
ES6/ES11知识点
前端·ecmascript·es6
假客套2 小时前
2025 后端自学UNIAPP【项目实战:旅游项目】3、API接口请求封装,封装后的简单测试以及实际使用
uni-app·旅游项目实战
2501_915373885 小时前
Vue 3零基础入门:从环境搭建到第一个组件
前端·javascript·vue.js
沙振宇7 小时前
【Web】使用Vue3开发鸿蒙的HelloWorld!
前端·华为·harmonyos
运维@小兵8 小时前
vue开发用户注册功能
前端·javascript·vue.js
蓝婷儿8 小时前
前端面试每日三题 - Day 30
前端·面试·职场和发展
oMMh8 小时前
使用C# ASP.NET创建一个可以由服务端推送信息至客户端的WEB应用(2)
前端·c#·asp.net
一口一个橘子9 小时前
[ctfshow web入门] web69
前端·web安全·网络安全
读心悦10 小时前
CSS:盒子阴影与渐变完全解析:从基础语法到创意应用
前端·css