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>
相关推荐
橙子家6 小时前
浏览器缓存之【身份与会话管理】:Cookies 和 Private state tokens
前端
To_OC7 小时前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode
最新资讯动态7 小时前
HDC 2026 | 对话鲸鸿动能:存量时代,品牌如何夺回营销“主动权”?
前端
最新资讯动态7 小时前
游戏出海,从产品走向体系
前端
最新资讯动态7 小时前
20人团队跑出百万DAU、大厂也来抢量:谁在鸿蒙生态跑出加速度
前端
最新资讯动态8 小时前
千万开发者背后,鸿蒙商业化的B面
前端
爱勇宝9 小时前
AI 时代:智商决定起点,情商决定走多远
前端·ai编程
kyriewen10 小时前
用了半年 Claude Code 后,我尝试关掉它写了一周代码——结果比想象中严重
前端·javascript·ai编程
IT_陈寒10 小时前
Vite的静态资源打包让我熬夜到三点,这坑千万别跳
前端·人工智能·后端
山河木马11 小时前
矩阵专题0-webGL中的矩阵
javascript·webgl·计算机图形学