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>