关于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>
相关推荐
Penge66610 分钟前
JavaScript:BOM 详解
前端
梯度下降者18 分钟前
Nuxt框架
vue.js·服务端渲染·全栈开发·混合渲染·nuxt框架
Penge66643 分钟前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge6661 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge6661 小时前
Sass 了解
前端
Penge6661 小时前
Webpack 打包从 0 到 1 实战笔记
前端
Penge6662 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge6662 小时前
Ant Design(Antd)了解
前端
wangruofeng2 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github
Penge6663 小时前
JavaScript 核心语法速通
前端