uniapp 中父组件调用子组件方法

24 篇文章 0 订阅

需求描述

随着开发的深入和代码的维护,为了某些功能的实现可以说是又秃了几根;接下来就说一说,通过 ref 实现父组件调用子组件的方法等。

1.父组件模板

​ 在父级模块的子组件上添加属性 ref 和 属性名 mySon (随意),调用时使用 this.$ref.(属性名).(子组件方法);

<template>
  <view class="">
    <son ref="mySon"></son>
    <button @click="fatherClick">父组件按钮</button>
  </view>
</template>
<script>
  import son from '@/components/son.vue'
  export default {
    components: {
      son
    },
    methods: {
      fatherClick() {
        this.$refs.mySon.sonClick("father call son");
      }
    }
  }
</script>

2.子组件模板

<template>
  <view class="">
    <text>子组件</text>
  </view>
</template>
<script>
  export default {
    name: 'son',
    methods: {
      sonClick(e) {
        console.log(e)
      }
    }
  }
</script>

1.父组件模板(Vue3)

<template>
  <view class="">
    <son ref="mySon"></son>
    <button @click="fatherClick">父组件按钮</button>
  </view>
</template>
<script lang="ts" setup>
  import son from '@/components/son.vue'
  
  const mySon=ref()
  
  const fatherClick=()=> {  mySon.value.sonClick("father call son")  }
</script>

2.子组件模板

<template>
  <view class="">
    <text>子组件</text>
  </view>
</template>
<script lang="ts" setup>

const sonClick = (e:string)=> { console.log(e) }

// 暴露变量
defineExpose({
	sonClick,
});
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shaoin_2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值