vue.js - 如何在 vue 3 脚本设置中的组件上使用 v-model

标签 vue.js vuejs3 vue-composition-api v-model vue-script-setup

我想添加一个 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和发出的事件 inputupdate: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/

相关文章:

css - Vue.js 转换 - 第一个入口不工作

javascript - 获取设置交叉引用

javascript - Vue js不触发onChange

typescript - 模板文字表达式的无效类型 "string | null"。发送授权时

javascript - 如何使用 Storybook 配置 VueJS + PostCss + Tailwind

javascript - 如何将 html 内容加载到 Quill 所见即所得编辑器中?

vue.js - 如何通过 setup() 发出多个参数?

vue.js - 如何在 vuejs3 应用程序的设置中调用方法?

typescript - 如何使用 Composition API 全局注册 Vue 3 组件?

vuejs3 - Vuedraggable如何在2个draggable之间交换项目