前言:以爷孙传值的例子来介绍在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:主要代码和详细讲解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b4a7a10237155d34afd63004f6d9de9d.png)