使用provide和inject 的方式让祖孙组件之间传值
祖组件:
<script setup lang='ts'>
import { provide, reactive } from "vue";
import Son from "./Son.vue";
const info = reactive({
name:'ccc',
age:10
})
provide("info",info)
const toSun=(value:number)=>{
console.log('获取孙组件的值',value)
}
provide('toSun',toSun)
</script>
<template>
<div class="box">
<p>父组件--{{info.age}}</p>
<Son />
</div>
</template>
<style scoped lang='scss'>
</style>
子组件
<script setup lang='ts'>
import Grandson from './Grandson.vue';
</script>
<template>
<div>
<p>子组件</p>
<Grandson />
</div>
</template>
<style scoped lang='scss'>
</style>
孙组件
<script setup lang='ts'>
import { inject } from "vue";
type obj = {
name:string,
age:number
}
let info = inject("info") as obj
let toSun = inject("toSun") as Function
const change=()=>{
info.age ++
toSun(info.age)
}
</script>
<template>
<div>
<p>孙组件--{{info.name}}--{{info.age}}</p>
<button @click="change">btn</button>
</div>
</template>
<style scoped lang='scss'>
</style>
记录一下