简介
- 这两个api一般一起使用,官网上曾说,这与React的Context非常相似 点击
- 他们用于跨组件传递数据
provide
- 他有两个参数,name(必须是字符串)和vaule
inject
2. 他也有两个参数,name和默认值(可选)
例子
代码
父组件
<script setup>
import { provide, ref } from 'vue';
import Child from "./子组件.vue"
const color = ref("red")
provide("color", color)
const changeColor = (_color) => {
color.value = _color
}
</script>
<template>
<h2>父组件</h2>
<div>当前的颜色为{{ color }}</div>
<button @click="changeColor('blue')">蓝色</button>
<button @click="changeColor('yellow')">黄色</button>
<button @click="changeColor('green')">绿色</button>
<child></child>
</template>
子组件
<script setup>
import GrandSon from "./孙组件.vue"
</script>
<template>
<h2>子组件</h2>
<grand-son></grand-son>
</template>
孙组件
<script setup>
import { inject } from 'vue';
// 与eventBus是两码事
const color = inject("color")
</script>
<template>
<h2>孙组件</h2>
<div :style="{color:color}">看我的颜色</div>
</template>
效果
- 当我们点击相应的按钮的时候,我们会发现孙组件就会拿到相应的变量