组件通信-v-model

  1. 概述:实现 父↔子 之间相互通信。

  2. 前序知识 ------ v-model的本质

html 复制代码
<!-- 使用v-model指令 -->
<input type="text" v-model="userName">

<!-- v-model的本质是下面这行代码 -->
<input 
  type="text" 
  :value="userName" 
  @input="userName =(<HTMLInputElement>$event.target).value"
>

3.(父组件)组件标签上的v-model的本质::moldeValueupdate:modelValue事件。

html 复制代码
<script setup lang="ts">
import { ref } from 'vue'
import AtInput from './AtInput.vue'
const username = ref('zhangsan')
</script>

<template>
    <div class="father">
        <h1>父组件</h1>
        <!-- 第一种写法 -->
        <AtInput v-model="username" />
        <!-- 第二种写法 -->
        <!-- <AtInput :modelValue="username" @update:modelValue="username = $event" /> -->
    </div>

</template>

(子组件) AtInput组件中:

html 复制代码
<script setup lang="ts">
// 接收props
defineProps(['modelValue'])
 // 声明事件
const emit= defineEmits(['update:modelValue'])
</script>

<template>
    <div class="input">
        <input type="text" 
            :value="modelValue"
            @input="emit('update:modelValue',(<HTMLInputElement>$event.target).value)"
        >
    </div>

</template>

4.也可以更换value,例如改成ming

javascript 复制代码
<!-- 也可以更换value,例如改成abc-->
<AtInputv-model:ming="userName"/>

<!-- 上面代码的本质如下 -->
<AtInput:ming="userName" @update:ming="userName = $event"/>

AtInput组件中

html 复制代码
<template>
    <input 
       type="text" 
       :value="ming" 
       @input="emit('update:abc',$event.target.value)"
    >
</template>

<script setup lang="ts" name="AtInput">
  // 接收props
  defineProps(['ming'])
  // 声明事件
  const emit = defineEmits(['update:ming'])
</script>

5.如果value可以更换,那么就可以在组件标签上多次使用v-model

<AtInput v-model:ming="userName" v-model:mima="password"/>

相关推荐
布谷歌2 分钟前
在java中实现c#的int.TryParse方法
java·开发语言·python·c#
while(1){yan}13 分钟前
网络基础知识
java·网络·青少年编程·面试·电脑常识
Ulana17 分钟前
计算机基础10大高频考题解析
java·人工智能·算法
黄俊懿24 分钟前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——@GlobalTransactional注解与@globalLock生效的原理
java·spring cloud·微服务·云原生·架构·系统架构·架构师
wheelmouse778828 分钟前
一个优雅、通用、零侵入的 CSV 导出工具类(Java 实战)
java·开发语言
cike_y1 小时前
JavaWeb-Request应用与Cookie&[特殊字符]️Session
java·开发语言·安全·java安全
hashiqimiya1 小时前
两个步骤,打包war,tomcat使用war包
java·服务器·前端
大筒木老辈子1 小时前
C++笔记---并发支持库(atomic)
java·c++·笔记
Cricyta Sevina1 小时前
Java Collection 集合进阶知识笔记
java·笔记·python·collection集合
BD_Marathon1 小时前
【JavaWeb】Servlet_url-pattern的一些特殊写法问题
java·开发语言·servlet