vue3组件通信(5)——$attrs

概述:通常用于当前组件的父组件和当前组件的子组件之间的通信;(祖—>孙)

存在三个组件:         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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值