vue3 父组件执行子组件的函数(读取子组件的所有数据)

父组件代码

<template>
  <div>
    <button @click="callChildFunction">调用子组件函数</button>
    <ChildComponent ref="childComponent"></ChildComponent> // ref="childComponent" 这个很重要
  </div>
</template>
<script>
  import ChildComponent from './ChildComponent.vue';
  export default {
    components: {
      ChildComponent,
    },
    methods: {
      callChildFunction() {
        this.$refs.childComponent.childFunction();
      },
    },
  };
</script>

<script>
import { getCurrentInstance  } from 'vue'; // 导入读取全局变量的方法
export default {
  setup() {
    const { proxy } = getCurrentInstance(); // 导出全局变量
    console.log(proxy.$refs.childComponent.childFunction());
  }
}
 
</script>

子组件代码

在子组件,只需要导出需要读取的就行了

<template>
  <div>
    {{ message }}
  </div>
</template>
<script>
  export default {
    data() {
      return {
        message: '我是子组件',
      };
    },
    methods: {
      childFunction() {
        console.log('子组件函数被调用!');
      },
    },
  };
</script>

<script>
export default {
  setup() {
    childFunction() {
        console.log('子组件函数被调用!');
      },
  return {childFunction} // 确保最后这个函数暴露出来
  }
}

</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值