我想添加一个 v-model
在一个组件上,但我收到了这个警告:
[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>
我试图reproduce this tutorial但我被卡住了,不知道我错过了什么。我要显示
{{ name }}
在 Parent.vue 组件中。你知道如何解决这个问题吗?
最佳答案
在 vue 3 value
Prop 已更改为 modelValue
和发出的事件 input
至 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.js - 如何在 vue 3 脚本设置中的组件上使用 v-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66737918/