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>
相关推荐
掘金安东尼11 小时前
让 JavaScript 更容易「善后」的新能力
前端·javascript·面试
掘金安东尼11 小时前
用 HTMX 为 React Data Grid 加速实时更新
前端·javascript·面试
灵感__idea13 小时前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
yinuo13 小时前
轻松接入大语言模型API -04
前端
袋鼠云数栈UED团队14 小时前
基于 Lexical 实现变量输入编辑器
前端·javascript·架构
cipher14 小时前
ERC-4626 通胀攻击:DeFi 金库的"捐款陷阱"
前端·后端·安全
UrbanJazzerati14 小时前
非常友好的Vue 3 生命周期详解
前端·面试
AAA阿giao14 小时前
从零构建一个现代登录页:深入解析 Tailwind CSS + Vite + Lucide React 的完整技术栈
前端·css·react.js
亦妤14 小时前
JS执行机制、作用域及作用域链
javascript
兆子龙15 小时前
像 React Hook 一样「自动触发」:用 Git Hook 拦住忘删的测试代码与其它翻车现场
前端·架构