5.组件间通信-$attrs(祖孙组件通信)

组件间通信-$attrs(祖孙组件通信)

父组件:

javascript 复制代码
<template>
  <div class="father">
    <h3>父组件</h3>
		<h4>a:{{a}}</h4>
		<h4>b:{{b}}</h4>
		<h4>c:{{c}}</h4>
		<h4>d:{{d}}</h4>
		<Child :a="a" :b="b" :c="c" :d="d" v-bind="{x:100,y:200}" :updateA="updateA"/>
  </div>
</template>
<script setup lang="ts" name="Father">
	import Child from './Child.vue'
	import {ref} from 'vue'
	let a = ref(1)
	let b = ref(2)
	let c = ref(3)
	let d = ref(4)
	function updateA(value:number){
		a.value += value
	}
</script>
<style scoped>
	.father{
		background-color: rgb(165, 164, 164);
		padding: 20px;
		border-radius: 10px;
	}
</style>

子组件:

javascript 复制代码
<template>
	<div class="child">
		<h3>子组件</h3>
		<h3>a:{{ a }}</h3>
		<h3>其他:{{$attrs.a}}</h3>
		<!-- 将父组件传的没有被props接收的值绑定给孙组件 -->
		<GrandChild v-bind="$attrs"/>
	</div>
</template>
<script setup lang="ts" name="Child">
	import GrandChild from './GrandChild.vue'
	defineProps(['a'])
</script>
<style scoped>
	.child{
		margin-top: 20px;
		background-color: skyblue;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 0 10px black;
	}
</style>

孙组件:

javascript 复制代码
<template>
	<div class="grand-child">
		<h3>孙组件</h3>
		<h4>a:{{ a }}</h4>
		<h4>b:{{ b }}</h4>
		<h4>c:{{ c }}</h4>
		<h4>d:{{ d }}</h4>
		<h4>x:{{ x }}</h4>
		<h4>y:{{ y }}</h4>
		<button @click="updateA(6)">点我将爷爷那的a更新</button>
	</div>
</template>
<script setup lang="ts" name="GrandChild">
	defineProps(['a','b','c','d','x','y','updateA'])
</script>
<style scoped>
	.grand-child{
		margin-top: 20px;
		background-color: orange;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 0 10px black;
	}
</style>
相关推荐
山河木马4 小时前
GPU自动处理专题4-填充覆盖区域(光栅化)
javascript·webgl·计算机图形学
悦儿遥遥雨14 小时前
PXE + Kickstart 无人值守批量部署系统
linux·javascript·nginx
31535669135 小时前
Superpowers:GPT-5.6 时代下的流程毒瘤
前端·后端
清秋5 小时前
全网最全 ECMAScript 攻略( 更新至 ES2026)
前端·javascript·编程语言
Cao_Ron5 小时前
用 SVG image symbol 画 ECharts graph 圆形节点
前端
hxy06015 小时前
React-Call让你的React组件像异步函数一样调用
前端·react.js
Hilaku6 小时前
为什么 AI 写前端时,总是优先选择 React,而不是 Vue?
前端·javascript·程序员
京东云开发者6 小时前
GPT-5.6、ChatGPT Work 与 Codex 更新食用指南
前端
Cao_Ron6 小时前
用 ECharts graph 画出卡片式矩形节点
前端
skiyee6 小时前
换个底座的 Wot Starter 居然让 AI 更懂项目!
前端·ai编程