vue3组件之间通信(五)——provide和inject的使用

63 阅读1分钟
前言:以爷孙传值的例子来介绍在setup函数和script setup语法糖中provide和inject的使用都是一样的。

1:使用语法

// 爷组件
import { defineComponent } from "vue"; // 1:引入
const fatherMsg = ref("father---张三");
function fatherProvideFunctin(params) {
  console.log("fatherd log", params);
}
// 2:爷组件中使用provide来传递属性和方法
provide("fatherProvideMsg", fatherMsg );
provide("fatherProvideFunctin",fatherProvideFunctin);

// 孙组件
import { inject } from "vue";  // 3:在子组件中引入inject
// 4:在孙组件中通过遍历来接收inject的值
let msg = inject("fatherProvideMsg");
console.log("msg", msg);
let handleLog = inject("fatherProvideFunctin");
await handleLog("参数");

2:主要代码和详细讲解

image.png