4.组件间通信-v-model

vue3组件间通信-v-model

父组件:

javascript 复制代码
<template>
  <div class="father">
    <h3>父组件</h3>
    <!-- <h4>{{ username }}</h4>
    <h4>{{ password }}</h4> -->
    <!-- v-model用在html标签上 -->
    <!-- <input type="text" v-model="username"> <br>
    <input type="text" :value="username" @input="username=(<HTMLInputElement>$event.target).value"> -->
    <!-- v-model用在组件标签上 -->
    <AtguiguInput v-model="username"/>
    <!-- 对于原生事件,$event就是事件对象,能$event.target.value
         对于自定义事件,$event就是触发事件时所传递的数据,不能$event.target.value,只能$event
    --> 
    <!-- <AtguiguInput 
      :modelValue="username" 
      @update:modelValue="username = $event"
    /> -->

    <!-- 修改modelValue -->
    <!-- <AtguiguInput v-model:ming="username" v-model:mima="password"/> -->
  </div>
</template>
<script setup lang="ts" name="Father">
	import { ref } from "vue";
  import AtguiguInput from './AtguiguInput.vue'
  // // 数据
  let username = ref('zhansgan')
  let password = ref('123456')
</script>
<style scoped>
.father {
  padding: 20px;
  background-color: rgb(165, 164, 164);
  border-radius: 10px;
}
</style>

子组件:

javascript 复制代码
<template>
  <input 
    type="text" 
    :value="modelValue"
    @input="emit('update:modelValue',(<HTMLInputElement>$event.target).value)"
  >
  <br>
   <!-- 对于原生事件,$event就是事件对象,能$event.target.value
         对于自定义事件,$event就是触发事件时所传递的数据,不能$event.target.value,只能$event
    --> 
  <input 
    type="text" 
    :value="mima"
    @input="emit('update:mima',(<HTMLInputElement>$event.target).value)"
  >
</template>
<script setup lang="ts" name="AtguiguInput">
  defineProps(['modelValue','mima'])
  const emit = defineEmits(['update:modelValue','update:mima'])
</script>

<style scoped>
  input {
    border: 2px solid black;
    background-image: linear-gradient(45deg,red,yellow,green);
    height: 30px;
    font-size: 20px;
    color: white;
  }
</style>
相关推荐
bonechips几秒前
React 组件通信:一套 TodoList 讲清 props 与回调
前端·react.js
渣波2 分钟前
别把 TodoList 写成面条代码!一文吃透 React 组件通信与状态驱动的核心内功
前端
2601_964702892 分钟前
Claude Opus 5 API 开发实战:对话、文本生成与结构化输出
java·服务器·前端
cellurw12 分钟前
20260724 六组件编译收尾与全局构建验证
前端
寒水馨16 分钟前
Windows下载、安装electron-v43.2.0(附安装包electron-v43.2.0-win32-x64.zip)
javascript·windows·typescript·electron·跨平台·桌面应用·chromium
用户29307509766924 分钟前
用React 完成Todos 的 组件应用:深入理解单向数据流与组件通信
前端
玉宇夕落37 分钟前
React 父子组件通信 Todo List 看透单向数据流与不可变数据
前端
软件开发技术深度爱好者37 分钟前
国际音标魔法实验室工具HTML5实现
前端·html5·英语学习
FogLetter38 分钟前
嘘!WebSocket正在“偷听”你的网络请求——全双工通信的魔法
前端·面试