关于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>
相关推荐
x***13392 小时前
【MyBatisPlus】MyBatisPlus介绍与使用
android·前端·后端
z***75154 小时前
【Springboot3+vue3】从零到一搭建Springboot3+vue3前后端分离项目之后端环境搭建
android·前端·后端
fruge5 小时前
仿写优秀组件:还原 Element Plus 的 Dialog 弹窗核心逻辑
前端
an86950015 小时前
vue新建项目
前端·javascript·vue.js
w***95496 小时前
SQL美化器:sql-beautify安装与配置完全指南
android·前端·后端
顾安r7 小时前
11.22 脚本打包APP 排错指南
linux·服务器·开发语言·前端·flask
万邦科技Lafite7 小时前
1688图片搜索商品API接口(item_search_img)使用指南
java·前端·数据库·开放api·电商开放平台
czhc11400756637 小时前
c# 1121 构造方法
java·javascript·c#
yinuo8 小时前
网页也懂黑夜与白天:系统主题自动切换
前端
Coding_Doggy8 小时前
链盾shieldchain | 项目管理、DID操作、DID密钥更新消息定时提醒
java·服务器·前端