VUE3 爷孙组件传值或者事件

要让孙组件直接调用爷组件中的某个函数或者值(本文演示事件,值为同理),可以使用 provide/inject 功能来实现。

以下是详细步骤:

1. 爷组件(Grandparent.vue):
   - 使用 `provide` 函数将需要共享的函数或数据注入到组件树中,以便后代组件可以访问它们。
   - 在 `provide` 函数中提供一个函数(例如 `handleFunction`),它将作为共享函数被传递给后代组件。

<!-- Grandparent.vue -->
<template>
  <div>
    <h2>Grandparent Component</h2>
    <Parent />
  </div>
</template>

<script>
import { defineComponent, provide } from "vue";
import Parent from "./Parent.vue";

export default defineComponent({
  setup() {
    // 定义需要共享的函数
    const handleFunction = () => {
      console.log("Function called from Grandparent");
    };

    // 使用 provide 函数将函数注入到组件树中
    provide("handleFunction", handleFunction);

    return {};
  },
  components: {
    Parent,
  },
});
</script>

2. 父组件(Parent.vue):
   - 不需要进行任何更改。

<!-- Parent.vue -->
<template>
  <div>
    <h2>Parent Component</h2>
    <Child />
  </div>
</template>

<script>
import { defineComponent } from "vue";
import Child from "./Child.vue";

export default defineComponent({
  components: {
    Child,
  },
});
</script>

3. 子组件(Child.vue):
   - 使用 `inject` 函数从爷组件中获取共享的函数。
   - 在需要的地方调用该函数。

<!-- Child.vue -->
<template>
  <div>
    <h2>Child Component</h2>
    <button @click="handleClick">Call Function</button>
  </div>
</template>

<script>
import { defineComponent, inject } from "vue";

export default defineComponent({
  methods: {
    handleClick() {
      // 从爷组件中获取共享的函数
      const handleFunction = inject("handleFunction");

      // 调用函数
      if (handleFunction) {
        handleFunction();
      }
    },
  },
});
</script>

通过这种方式,孙组件可以直接调用爷组件中的特定函数。在孙组件的 `handleClick` 方法中,通过 `inject` 函数从爷组件中获取共享的函数 `handleFunction`,然后可以直接调用该函数。

请确保在爷组件使用 `provide` 注入函数时,命名要保持一致。在孙组件中使用 `inject` 时,传递的参数也要与提供的名称相同。

这样,孙组件就可以直接调用爷组件中的函数了。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值