关于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>
相关推荐
xxy-mm5 小时前
Javascript 中的继承
开发语言·javascript·ecmascript
锋行天下6 小时前
公司内网部署大模型的探索之路
前端·人工智能·后端
1024肥宅7 小时前
手写 EventEmitter:深入理解发布订阅模式
前端·javascript·eventbus
EveryPossible8 小时前
google搜索框
vue.js
海市公约8 小时前
HTML网页开发从入门到精通:从标签到表单的完整指南
前端·ide·vscode·程序人生·架构·前端框架·html
3秒一个大8 小时前
HTML5 与 JavaScript 中的二进制数据处理:ArrayBuffer 与 TextEncoder/Decoder 实践
javascript
purpleseashell_Lili9 小时前
如何学习 AG-UI 和 CopilotKit
javascript·typescript·react
行云流水6269 小时前
前端树形结构实现勾选,半勾选,取消勾选。
前端·算法
diudiu_339 小时前
web漏洞--认证缺陷
java·前端·网络
阿珊和她的猫9 小时前
<video>` 和 `<audio>` 标签的常用属性解析
前端