1、v-model
v-model的底層原理:是:value值和@input事件的結合
$event到底是啥?啥時候能.target
- 對于原生事件,$event就是事件對象 ,能.target
- 對應自定義事件,$event就是觸發事件時,所傳遞的數據,不能.target
<template><div class="father"><h3>父組件</h3><!-- v-model用在html標簽上--><input type = "text" v-model="username"><!-- 雙向綁定 --><!-- <input type="text" :value="username" @input="username=(<HTMLInput Element>$event.target).value">--><!-- v-model用在組件標簽上--><AtMyInput v-model="username" /><!--等價于下面--><AtMyInput :modelValue="username"@update:modelValue="username = $event"/><!-- 修改modelvalue --><AtMyInput v-model:qwe="username" /><div>
</template><script setup lang="ts" name="Father">import {ref} from "vue";// 數據let username = ref('zhangsan')</script>>> AtMyInput.vue<template><input type="text" <!-- :value = "modelValue" -->:value = "qwe"<!-- @input="emit('update:modelValue',(<HTMLInput Element>$event.target).value)"> -->
@input="emit('update:qwe',(<HTMLInput Element>$event.target).value)">
</template><script setup lang="ts" name="AtMyInput"><!-- defineProps(['modelValue'])-->
defineProps(['qwe'])<!-- const emit = defineEmits(['update:modelValue']) -->const emit = defineEmits(['update:qwe'])
</script>
2、$attrs
1、概述:$attrs用于實現當前組件的父組件,向當前組件的子組件通信(祖->孫)
2、具體說明:$attrs是一個對象,包含所有父組件傳入的標簽屬性。
注意:$attrs會自動排除props中聲明的屬性(可以認為聲明過的props被子組件自己“消費”了)
<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>
<template><div class = "child"><h3>子組件</h3><h4>a:{{a}} </h4><GrandChild v-bind="$attrs"/></div>
</template><script setup lang="ts" name="Child">import GrandChild from './GrandChild.vue'defineProps(['a'])
</script>
<template><div class = "father"><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><Child/></div>
</template><script setup lang="ts" name="Father">import Child from './Child.vue'defineProps(['a','b','c','d','x','y','updateA'])</script>