wit*_*ein 25 vue.js v-model vuejs3 vue-composition-api vue-script-setup
我想v-model在组件上添加 a 但收到此警告:
[Vue warn]: Component emitted event "input" but it is neither declared in the emits option nor as an "onInput" prop.
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
[Vue warn]: Component emitted event "input" but it is neither declared in the emits option nor as an "onInput" prop.
Run Code Online (Sandbox Code Playgroud)
// 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>
Run Code Online (Sandbox Code Playgroud)
我试图重现本教程,但我被困住了,不知道我错过了什么。
{{ name }}我想在Parent.vue组件中显示。您知道如何解决这个问题吗?
Bou*_*him 42
版本 >= 3.3(3.4 版本稳定)
可以直接使用defineModel宏(v3.4稳定):
子.vue:
<script setup>
const modelValue = defineModel()
</script>
<template>
<input v-model="modelValue" />
</template>
Run Code Online (Sandbox Code Playgroud)
版本 < 3.3
在 vue 3 中,valueprop 已更改为 ,modelValue并且发出的事件已更改input为update:modelValue:
家长.vue
<Child v-model="name" label="Name" />
儿童.vue
<template>
<input
class="input"
type="text"
:placeholder="props.label"
:value="props.modelValue"
v-on:input="updateValue($event.target.value)"
/>
</template>
<script setup>
const props = defineProps({
modelValue: String
})
const emit = defineEmits(['update:modelValue'])
function updateValue(value) {
emit('update:modelValue', value)
}
</script>
Run Code Online (Sandbox Code Playgroud)
小智 15
我也喜欢与计算一起使用
<template>
<div>
<input v-model="model">
</div>
</template>
<script setup>
import { computed } from 'vue'
const props = defineProps({
modelValue: {
type: [String, Number],
default: ''
}
})
const emit = defineEmits(['update:modelValue'])
const model = computed({
get () {
return props.modelValue
},
set (value) {
return emit('update:modelValue', value)
}
})
</script>
Run Code Online (Sandbox Code Playgroud)