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>
相关推荐
_kerneler10 分钟前
cgroup :限制cpu原理
java·服务器·前端
yingyima35 分钟前
AWK 速查手册:不仅仅是文本处理,更是性能与简洁的抉择
前端
悟空瞎说35 分钟前
WebSocket 前端丢包处理实战:原理与完整代码实现
前端
秋天的一阵风37 分钟前
✨ 原来文本转换可以这么丝滑!UnifiedJS 实战指南来了
前端·github·markdown
南川琼语1 小时前
HTTP——AJAX
前端·javascript·ajax
用户47949283569151 小时前
专升本前端毕业 1 年,从初创到大厂,我的开源项目上了 github trending,顺便聊聊做开源的收获
前端·后端·github
Ashley的成长之路1 小时前
前端性能优化实战手册·第1篇:从 Lighthouse 60 到 95 的完整路径
前端·性能优化
思码梁田1 小时前
CSS letter-spacing 属性详解:掌控字符之间的呼吸感
前端·css
大尚来也2 小时前
React Hooks全解析:告别繁琐Class组件
前端·react.js·前端框架
不简说2 小时前
JS 代码技巧 vol.2 — 20 个数组/对象/字符串/正则的实用技巧
前端·javascript·面试