欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > vue3 父子组件传值双向绑定

vue3 父子组件传值双向绑定

2025/6/15 19:53:07 来源:https://blog.csdn.net/djh052900/article/details/148628646  浏览:    关键词:vue3 父子组件传值双向绑定

本示例基于vue3 + element-plus

核心语法:defineModel()

  • 仅在 3.4+ 中可用

这个宏可以用来声明一个双向绑定 prop,通过父组件的 v-model 来使用。

 效果demo:

 

// 父组件
<template><div class="home-container"><h1>home</h1><el-input v-model="input1" style="width: 240px" placeholder="Please input1" />{{ input1 }}<br><el-input v-model="input2" style="width: 240px" placeholder="Please input2" />{{ input2 }}<br><el-input v-model="input3" style="width: 240px" placeholder="Please input3" />{{ input3 }}<Childrenv-model:="input1"v-model:input2="input2"v-model:input3="input3"></Children></div>
</template><script setup>
import { ref } from 'vue';
import Children from '@/components/children.vue';const input1 = ref('');
const input2 = ref('');
const input3 = ref();
</script>// 子组件
<template><h1>children 子组件</h1><el-input v-model="modelValue" style="width: 240px" placeholder="modelValue" />{{ modelValue }}<br><el-input v-model="modelValue2" style="width: 240px" placeholder="modelValue2" />{{ modelValue2 }}<br><el-input v-model="modelValue3" style="width: 240px" placeholder="modelValue3" />{{ modelValue3 }}</template><script setup>
const modelValue = defineModel();
const modelValue2 = defineModel('input2');
const modelValue3 = defineModel('input3',{default:'默认值'});
</script>

input3

如果为 defineModel prop 设置了一个 default 值且父组件没有为该 prop 提供任何值,会导致父组件与子组件之间不同步。在上面的示例中,父组件的 input3 是 undefined,而子组件的 modelValue3默认值 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词