概述:通常用于当前组件的父组件和当前组件的子组件之间的通信;(祖—>孙)
存在三个组件: father child grandchild
1.attrs介绍(用来保存传递过程中未被接收的数据)
father组件定义的响应式数据,可以通过props通信方式进行传递,child组件可以通过defineprops进行接收,但是当child组件不接收时,father组件传递的数据将被保存到 $attrs 中:
2.实现孙获取父传递的数据
father组件向子组件传递数据以后,子组件不接收将全部保存到 $attrs 中,子组件通过向孙组件传递 $attrs ,从而达到father向grandchild传递数据;
// 父组件向子组件传递数据 v-bind="{x:100,y:200}" 等价于 :x='100' :y='200'
<Child :a="a" :b="b" :c="c" v-bind="{x:100,y:200}" :adda="adda"/>
// 子组件不使用父组件传递的数据,并将数据传给孙组件
<Grandchild v-bind="$attrs"/>
//孙组件部分使用子组件传递的数据
<template>
<div class="grand-child">
<h3>孙组件</h3>
<h2>{{a}}</h2>
<h2>{{b}}</h2>
<h2>{{c}}</h2>
</div>
</template>
<script setup lang="ts">
defineProps(['a','b','c','adda'])
</script>
上图为grandchild组件:可以看到使用了的参数被放在了props中,未使用的参数在attrs中;
3.孙组件向父组件传递数据 利用函数传参(和第一节props传参一样)
// 父组件定义一个带参数的函数,通过props传递给子组件;
<template>
<div class="father">
<h3>父组件</h3>
<Child :a="a" :b="b" :c="c" v-bind="{x:100,y:200}" :adda="adda"/>
</div>
</template>
<script setup lang="ts">
import Child from "./child.vue";
import {ref} from "vue";
function adda(value:string){
a.value+=value
}
</script>
// 子组件不使用通过$attrs传递给孙组件;
<template>
<div class="child">
<h3>子组件</h3>
<h2>{{$attrs}}</h2>
<Grandchild v-bind="$attrs"/>
</div>
</template>
<script setup lang="ts">
import Grandchild from "./grandchild.vue";
</script>
// 孙组件 defineprops 使用函数,并在合适的地方调用函数传入参数;
<template>
<div class="grand-child">
<h3>孙组件</h3>
<button @click="adda(6)" >点我a加6</button>
</div>
</template>
<script setup lang="ts">
defineProps(['adda'])
</script>