关于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>
相关推荐
Hammer Ray2 小时前
SourceMap知识点
javascript·sourcemap
西洼工作室2 小时前
项目环境变量配置全攻略
前端
阿珊和她的猫2 小时前
Webpack 优化:构建速度与包体积的双重提升
前端·webpack·node.js
阿珊和她的猫2 小时前
Webpack 打包体积优化:让应用更轻量、更高效
前端·webpack·状态模式
im_AMBER2 小时前
Vite + React 项目启动深度踩坑指南
前端·学习·react.js·前端框架
Hammer Ray2 小时前
前端开发基础概念(React)
前端·react.js·前端框架
Sunlightʊə5 小时前
2.登录页测试用例
运维·服务器·前端·功能测试·单元测试
Code Crafter5 小时前
ES6-ES14 新特性速查
前端·ecmascript·es6
Lhuu(重开版6 小时前
CSS从0到1
前端·css·tensorflow
CDwenhuohuo6 小时前
微信小程序里用 setData() 修改数据并打印输出 的几种写法
javascript·微信小程序·小程序