本文介绍了如何在 vue 3 脚本设置中的组件上使用 v-model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在一个组件上添加一个 v-model
但我收到了这个警告:
I want to add a v-model
on a component but I got this warning:
[Vue warn]: Component emitted event "input" but it is neither declared in the emits option nor as an "onInput" prop.
这是我的代码:
// Parent.vue
<template>
<h2>V-Model Parent</h2>
<Child v-model="name" label="Name" />
<p>{{ name }}</p>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const name = ref('')
</script>
// Child.vue
<template>
<input
class="input"
type="text"
:placeholder="props.label"
:value="props.value"
v-on:input="updateValue($event.target.value)"
/>
</template>
<script setup>
import { defineProps, defineEmit } from 'vue'
const props = defineProps({
label: String,
value: String
})
const emit = defineEmit('input')
function updateValue(value) {
emit('input', value)
}
</script>
我试图重现本教程但我被卡住了,不知道我错过了什么.
I was trying to reproduce this tutorial but I'am stuck and got no idea what I am missing.
我想在 Parent.vue 组件中显示 {{ name }}
.你知道如何解决这个问题吗?
I want to display {{ name }}
in the Parent.vue component. Do you got an idea how to solve this?
推荐答案
在 vue 3 中 value
属性已更改为 modelValue
并且发出的事件 input
到 update:modelValue
:
In vue 3 value
prop has been changed to modelValue
and the emitted event input
to update:modelValue
:
// Child.vue
<template>
<input
class="input"
type="text"
:placeholder="props.label"
:value="props.modelValue"
v-on:input="updateValue($event.target.value)"
/>
</template>
<script setup>
import { defineProps, defineEmit } from 'vue'
const props = defineProps({
label: String,
modelValue: String
})
const emit = defineEmit(['update:modelValue'])
function updateValue(value) {
emit('update:modelValue',value)
}
</script>
这篇关于如何在 vue 3 脚本设置中的组件上使用 v-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!