关于vue3使用prop传动态参数时父子数据不同步更新问题

子:

html 复制代码
<template>
  <div>
    <h3>子组件</h3>
    <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['update:modelValue'])
</script>

父:

html 复制代码
<template>
  <div>
    <h3>父组件</h3>
    <ChildComponent v-model:modelValue="message" />
    <p>子组件输入的内容:{{ message }}</p>
  </div>
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'

let message = ''
</script>

原文地址:vue3中利用v-model实现父子组件之间的数据同步_vue3父子组件传值实时更新-CSDN博客

使用注意(动态绑定失效的例子):

父组件中传递的参数在 组件中通过重新创建参数接收传递的参数 ,再绑定到页面。将导致数据无法实现动态绑定

html 复制代码
<template>
  <div>
    <h3>子组件</h3>
    <input :value="propModelValue" @input="$emit('update:modelValue', $event.target.value)">
  </div>
</template>

<script setup>
import { defineProps, defineEmits,ref } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const propModelValue=ref(prop.modelValue)

const emits = defineEmits(['update:modelValue'])
</script>
相关推荐
dreams_dream3 分钟前
vue2头部布局示例
前端·html
山雀~11 分钟前
React实现列表拖拽排序
前端·react.js·前端框架
前端世界11 分钟前
前端路由切换不再白屏:React/Vue 实战优化全攻略(含可运行 Demo)
前端·vue.js·react.js
Prosper Lee21 分钟前
前端基础(四十三):文本数据解析为键值对
开发语言·前端·javascript
我的收藏手册29 分钟前
Web与Nginx网站服务
运维·前端·nginx
JarvanMo40 分钟前
Flutter 应用程序中的无声杀手:为什么每个开发者都害怕这个文件
前端
伍哥的传说42 分钟前
Uni-App + Vue onLoad与onLaunch执行顺序问题完整解决方案 – 3种实用方法详解
javascript·vue.js·uni-app·事件总线·onlaunch·onload·promise状态管理
小桥风满袖1 小时前
极简三分钟ES6 - 数组遍历
前端·javascript
艾小码1 小时前
彻底搞懂 Vue 生命周期:从 created 到 unmounted 的完整指南
前端·javascript·vue.js
GHOME1 小时前
复习-网络协议
前端·网络协议·面试