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>
相关推荐
Winwin几秒前
哈?Boolean能作为回调函数?
javascript
我麻烦大了几秒前
实现一个简单的Vue响应式
前端·vue.js
Shartin4 分钟前
CPT208-Human-Centric Computing: Prototype Design Optimization原型设计优化
开发语言·javascript·原型模式
独立开阀者_FwtCoder8 分钟前
你用 Cursor 写公司的代码安全吗?
前端·javascript·github
dme.16 分钟前
Javascript之DOM操作
开发语言·javascript·爬虫·python·ecmascript
Cacciatore->18 分钟前
React 基本介绍与项目创建
前端·react.js·arcgis
摸鱼仙人~20 分钟前
React Ref 指南:原理、实现与实践
前端·javascript·react.js
teeeeeeemo21 分钟前
回调函数 vs Promise vs async/await区别
开发语言·前端·javascript·笔记
贵沫末40 分钟前
React——基础
前端·react.js·前端框架
aklry1 小时前
uniapp三步完成一维码的生成
前端·vue.js