关于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>
相关推荐
万少35 分钟前
使用Trae轻松安装openclaw的教程-附带免费token
前端·openai·ai编程
颜酱1 小时前
一步步实现字符串计算器:从「转整数」到「带括号与优化」
javascript·后端·算法
浪浪山_大橙子1 小时前
OpenClaw 十分钟快速,安装与接入完全指南 - 推荐使用trae 官方 skills 安装
前端·人工智能
忆江南1 小时前
iOS 可视化埋点与无痕埋点详解
前端
离开地球表面_991 小时前
金三银四程序员跳槽指南:从简历到面试再到 Offer 的全流程准备
前端·后端·面试
_柳青杨1 小时前
跨域获取 iframe 选中文本?自己写个代理中间层,再也不求后端!
前端
比尔盖茨的大脑1 小时前
事件循环底层原理:从 V8 引擎到浏览器实现
前端·javascript·面试
天才熊猫君1 小时前
Vue3 命令式弹窗原理和 provide/inject 隔离机制详解
前端
bluceli1 小时前
Vue 3 Composition API深度解析:构建可复用逻辑的终极方案
前端·vue.js
程序员ys1 小时前
前端权限控制设计
前端·vue.js·react.js