使用v-bind替代v-model时,Vue子组件如何接收值?
用v-bind替代v-model给组件传值的实现方法
核心逻辑
v-model是Vue的语法糖,本质等价于同时绑定:modelValue prop和@update:modelValue事件。如果只需要单向传值(用v-bind),直接绑定组件已声明的modelValue prop即可——不需要用bindValue,因为你的组件根本没定义这个prop,自然无法捕获值。
具体实现
- 组件代码无需修改
你的myInput.vue原代码完全可以保留,因为已经通过defineProps声明了modelValue作为接收值的prop:
<template> <input type="text" :value="modelValue" /> </template> <script setup> const props = defineProps({ modelValue: { type: [String, null], required: true } }) </script>
- 父组件用v-bind绑定
modelValue
在父组件中,直接用v-bind:modelValue(或简写:modelValue)传递数据即可:
<template> <!-- 简写形式 --> <my-input :modelValue="yourData" /> <!-- 完整v-bind写法 --> <my-input v-bind:modelValue="yourData" /> </template> <script setup> import MyInput from './myInput.vue' // 示例数据 const yourData = "hello world" </script>
为什么bindValue不生效?
组件只会识别自己通过defineProps声明的prop名称,你的组件只声明了modelValue,没有bindValue,所以绑定这个名称自然无法获取到值。
内容的提问来源于stack exchange,提问作者gespinha
相关产品推荐
相关产品推荐

