关于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>
相关推荐
Anastasiozzzz38 分钟前
阿亮随手记:动态条件生成Bean
java·前端·数据库
Highcharts.js1 小时前
数据之美:用Highcharts打造专业级弧线图
javascript·数据库·highcharts·图表开发·弧线图
mclwh1 小时前
关于React-Konva 报:Text components are not supported....错误的问题
前端·react.js
SuperEugene2 小时前
错误处理与 try/catch:真实项目里应该捕什么错?
前端·javascript·面试
Amumu121382 小时前
CSS引入方式
前端·css
我是Superman丶2 小时前
【Demo】✋ 数字手势识别 Html
前端·html
HelloReader3 小时前
Leptos + Tauri 2 前端配置Trunk + SSG + 移动端热重载一次打通(Leptos 0.6 口径)
前端
HelloReader3 小时前
Next.js + Tauri 2 用 Static Export 把 React 元框架装进桌面/移动端
前端
Wect3 小时前
从输入URL到页面显示的完整技术流程
前端·面试·浏览器
没有bug.的程序员3 小时前
自动化测试之魂:Selenium 与 TestNG 深度集成内核、Page Object 模型实战与 Web UI 交付质量指南
前端·自动化测试·selenium·ui·testng·page·object