我想在一个组件上添加一个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相关问答推荐

Nuxt3 Build . put文件夹保持空,没有从.nuxt复制任何内容

如何将 cogo toast PRIVE集成到nuxt3中?

保持页面重新加载之间的状态

Vue 3:插槽属性 - 可以通过 props 传递数据吗?

Vue 3 范围滑块中的多个值

我在表格中创建了一个包含信息的新行,但在 Cypress e2e 测试中我无法获得最后一行(新行)

使用计算(computed)属性更改视图

如何在Vue js 3中根据API响应替换react 值

使用 v-slot:body 时 Vuetify v-data-table 没有响应

使用 vue-cli 遇到无法推断解析器错误

apache上的Vue-router,子目录下的SPA,只能通过重定向访问页面

即使在客户端设置 Access-Control-Allow-Origin 或其他 Access-Control-Allow-* 标头后也出现 CORS 错误

vuejs中通过变量动态调用方法

Proxy代理在 Vue 3 的控制台中是什么意思?

如何在 Vuex 中获取 Vue 路由参数?

简单的点击功能不触发

过渡后的 v-if 下方的过渡元素

Vue.js webpack:如何获取目录中的文件列表?

更改事件上的 Select2 在 Vuejs 中不起作用

v-if 未在计算(computed)属性上触发