实现跨层级组件(祖孙)间通信
src\App.vue
<template>
<div>
<h2>provide 与 inject</h2>
<p>p当前的颜色:{{color}}</p>
<button @click="color='red'">红色</button>
<button @click="color='yellow'">黄色</button>
<button @click="color='green'">绿色</button>
<hr>
<Son />
</div>
</template>
<script lang="ts">
import { defineComponent, provide, ref } from 'vue'
import Son from './components/Son.vue'
export default defineComponent({
components: { Son },
name: 'App',
setup() {
const color = ref('red')
// 提供
provide('color', color)
return { color }
},
})
</script>
src\components\Son.vue
<template>
<h3>Son子集组件</h3>
<GrandSon />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import GrandSon from './GrandSon.vue'
export default defineComponent({
components: { GrandSon },
name: 'Son',
setup() {
return {}
},
})
</script>
src\components\GrandSon.vue
<template>
<h3 :style="{color}">GrandSon孙子组件</h3>
</template>
<script lang="ts">
import { defineComponent, inject } from 'vue'
export default defineComponent({
name: 'GrandSon',
setup() {
// 注入
const color = inject('color')
return { color }
},
})
</script>