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>
相关推荐
沐风。561 分钟前
通过js动态更新css变量
javascript·css·tensorflow
BD_Marathon2 分钟前
【JavaWeb】CSS_三种引入方式
前端·css
excel2 分钟前
# Vue 渲染系统的四个关键阶段:从模板编译到新旧 VDOM Patch 的完整机制解析
前端
cos3 分钟前
我的 Claude Code 使用小记 2
前端·ai编程·claude
Dreamboat-L6 分钟前
ES6 (ECMAScript 2015+)
前端·ecmascript·es6
凤凰战士芭比Q1 小时前
web中间件——(二)Nginx(高级功能、优化)
前端·nginx·中间件
阿珊和她的猫1 小时前
表单数据验证:HTML5 自带属性与其他方法的结合应用
前端·状态模式·html5
谷粒.2 小时前
Cypress vs Playwright vs Selenium:现代Web自动化测试框架深度评测
java·前端·网络·人工智能·python·selenium·测试工具
Hy行者勇哥3 小时前
HTML5 + 原生 CSS + 原生 JS 网页实现攻略
javascript·css·html5
小飞侠在吗8 小时前
vue props
前端·javascript·vue.js