vue3 父子孙组件之间的方法的调用

  • 将子组件、孙组件的方法使用defineExpose抛出
  • 对子组件、孙组件绑定ref属性
  • 通过ref属性对组件中抛出的方法进行调用

父组件

<template>
  <div>
    <Children ref="childrenFn"></Children>
  </div>
</template>
<script lang="ts" setup>
  import Children from './children.vue';
  import { ref, onMounted } from 'vue';

  const childrenFn = ref<any>(null);

  onMounted(() => {
    handleChildren();
  });
  function handleChildren() {
    childrenFn.value.initChildren();
    console.log('此处调用子组件的方法');
  }
</script>

子组件

<template>
  <div>
    <Grandson ref="grandsonFn"></Grandson>
  </div>
</template>
<script setup>
  import Grandson from './grandson.vue';
  import { ref, onMounted } from 'vue';

  const grandsonFn = ref(null);
  function initChildren() {
    grandsonFn.value.initGrandson();
    console.log('此处调用孙组件的方法');
  }
  /**
   * 将子组件的方法暴露出去
   */
  defineExpose({
    initChildren,
  });
</script>
<style lang="scss" scoped></style>

孙组件

<template>
  <div> </div>
</template>
<script setup>
  import { ref, onMounted } from 'vue';

  function initGrandson() {
    console.log('此处是孙组件操作');
  }
  /**
   * 将孙组件的方法暴露出去
   */
  defineExpose({
    initGrandson,
  });
</script>
<style lang="scss" scoped></style>

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 3中,组件可以通过props属性向子组件传递数据,而子组件可以通过$emit方法组件发送信息。下面是一个简单的示例来说明父子组件之间如何调用方法: 在组件中,首先需要在子组件上定义一个ref属性,用于获取子组件实例的引用。然后,在需要调用组件方法的地方,可以通过该引用来调用组件方法。 ```vue <template> <div> <ChildComponent ref="child"></ChildComponent> <button @click="callChildMethod">调用组件方法</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, methods: { callChildMethod() { this.$refs.child.childMethod(); // 调用组件方法 }, }, }; </script> ``` 在子组件中,需要将需要调用方法定义在methods选项中,并通过$emit方法组件发送消息。 ```vue <template> <div> <button @click="childMethod">子组件方法</button> </div> </template> <script> export default { methods: { childMethod() { this.$emit('childMethodCalled'); // 向组件发送消息 }, }, }; </script> ``` 在组件中,可以通过监听子组件的事件来接收消息。 ```vue <template> <div> <ChildComponent @childMethodCalled="handleChildMethodCalled"></ChildComponent> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent, }, methods: { handleChildMethodCalled() { // 处理子组件方法调用 }, }, }; </script> ``` 通过以上方式,组件就可以调用组件方法了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值