关于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>
相关推荐
SailingCoder40 分钟前
【封闭结束1】端到端交付:Agent 一次请求如何走完全链路
前端·安全·ai·面试·agent·harness
风骏时光牛马3 小时前
AI多模块协同自动化工作流
前端
zhangminghuan3 小时前
前端面试应对技巧
前端·面试·职场和发展
计算机魔术师3 小时前
潜伏14年的PHP致命洞,AI跑两天就交卷了
前端
IT_陈寒3 小时前
Vue的这个响应式陷阱我居然现在才发现
前端·人工智能·后端
Python自动化直播4 小时前
智能脚本批量管理拆开看:导入、导出、重写、试听
前端·python·ai·秒播
开开心心就好5 小时前
发票信息录入太麻烦?离线工具一键转表格
运维·服务器·前端·pdf·ocr·maven·intellij-idea
এ慕ོ冬℘゜5 小时前
ES Promise.all/ Promise.race
前端·javascript·elasticsearch
喜欢打篮球的普通人6 小时前
LLVM 前端与优化层:Clang 如何把 C 代码变成 IR
c语言·前端·状态模式