-
概述:
$attrs
用于實現當前組件的父組件,向當前組件的子組件通信(爺→孫)。 -
具體說明:
$attrs
是一個對象,包含所有父組件傳入的標簽屬性。注意:
$attrs
會自動排除props
中聲明的屬性(可以認為聲明過的props
被子組件自己“消費”了)
父組件:
<template><div class="father"><h3>父組件</h3><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){a.value = value}
</script>
?子組件
<template><div class="child"><h3>子組件</h3><GrandChild v-bind="$attrs"/></div>
</template><script setup lang="ts" name="Child">import GrandChild from './GrandChild.vue'
</script>
孫組件:
<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(666)">點我更新A</button></div>
</template><script setup lang="ts" name="GrandChild">defineProps(['a','b','c','d','x','y','updateA'])
</script>