如何在 Vue 3 中将 v 模型值传递给子组件



如何将v-model值从父组件传递到子组件的子组件?

母组件

<ChildElement v-model="name" />
<script>
import { ref } from "vue";
export default {
setup() {
const name = ref('Nagisa')
}
};
</script>

子组件

<AnotherChildComponent :value="value"/>
<script>
export default {
props: {
value: {
type: String,
default: ""
}
},
emits: ['update:modelValue']
};
</script>

AnotherChild组件

<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
<script>
export default {
props: {
modelValue: {
type: String,
default: ""
}
},
emits: ['update:modelValue'],
setup() {
}
};
</script>

当我想从AnotherChild组件更新父组件名称值时,这是有效的,但是默认名称值("Nagisa"(不会在AnotherChild组件中呈现,只是在输入中保持空字符串。

Vuex不是选项,我想直接从父组件传递。谢谢你的帮助。

当您想要传递任何组件属性时,您需要使用您在子组件的props对象中输入的确切名称。例如

AnotherChild组件的设置中,您有一个名为modelValue的道具,默认值为空字符串。

props: {
modelValue: {
type: String,
default: ""
}
},

但是,在它的父元素ChildComponent中,您传递名称为的值,

<AnotherChildComponent :value="value"/>

这将不起作用,因为在AnotherChild组件中没有任何名为value的道具,因此modelValue使用其默认值空字符串。您需要将值作为属性与道具名称一起传递,如下所示:

<AnotherChildComponent :model-value="value"/>

这也适用于组件的父级等等…

最新更新