我想在一个组件上添加一个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 }}.vue组件.你知道怎么解决这个问题吗?

推荐答案

在vue 3中,valueprops 已更改为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, defineEmits } from 'vue'

const props = defineProps({
  modelValue: String
})

const emit = defineEmits(['update:modelValue'])

function updateValue(value) {
  emit('update:modelValue', value)
}
</script>

Vue.js相关问答推荐

如何配置nuxt 3,以便当我直接打开用nPM run generate生成的静态页面时,它可以正常工作?

使用插槽的VUE 3工作台

vue3 输入标签给出错误 Vue.use 不是函数

vue3 ssr 不返回纯 html

在 bootstrap-vue 中渲染自定义样式

我可以在未注册的组件上构建 Vue.js 失败吗?

Defer推迟执行,直到外部脚本加载到 Vue.js

指定一个 vue-cli vue.config.js 位置

正确使用 Vue $refs

使用 vuex 更新数据

如何将对象作为props传递并让组件更新子对象

React.js 是否有类似 Vue.js

在 Vuejs 中计算 DOM 元素之间距离的最佳方法是什么?

动态注册本地 Vue.js 组件

加载时焦点文本框上的 Vue.js

按键删除对象不会更新vue组件

中文而不是英文的Element UI分页

如何在 vue.js 中进行嵌入?

脚本npm run dev和npm run watch是做什么用的?

Vue.js 无法读取 null 的属性 length长度