如何将 v-model 绑定到包含输入的子组件

Mig*_*der 2 javascript vue.js babeljs

我有一些看起来像这样的组件。

<template>
  <q-layout>
    <v-input v-model="something" />
  </q-layout>
</template>

<script>
import { QLayout } from 'quasar'
import { Input } from 'vedana'

export default {
  name: 'index',
  components: {
    QLayout,
    Input
  },
  data () {
    return {
      something: ''
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这个 v-input 组件看起来像这样:

<template>
    <input
        :type="type ? type : 'text'"
        class="v-input"/>
</template>

<script>
export default {
    props: ['type'],
    name: 'v-input'
}
</script>
Run Code Online (Sandbox Code Playgroud)

当我将数据输入到 input 中时,something它不会绑定到 v-input 内部的 input 值中的任何内容。

我如何实现这一目标?

acd*_*ior 5

要启用v-model内部组件value的使用,必须带一个属性

使用, not将绑定value到内部(这会改变来自父级的道具)。当内部被编辑时,为父级发出一个事件,以更新其值(事件将更新父级上的变量)。<input>:valuev-model<input>inputinputv-model

此外,如果您有typeprop的默认值,请在 中声明它props,而不是在模板中。

这是您的代码应该如何

<template>
    <input
        :type="type"
        :value="value"
        @input="$emit('input', $event.target.value)"
        class="v-input" />
</template>

<script>
export default {
    props: {
      type: {default() { return 'text'; }},
      value: {}                              // you can also add more restrictions here
    },
    name: 'v-input'
}
</script>
Run Code Online (Sandbox Code Playgroud)

关于什么props可以拥有的信息:组件/使用道具传递数据

下面演示。

<template>
    <input
        :type="type"
        :value="value"
        @input="$emit('input', $event.target.value)"
        class="v-input" />
</template>

<script>
export default {
    props: {
      type: {default() { return 'text'; }},
      value: {}                              // you can also add more restrictions here
    },
    name: 'v-input'
}
</script>
Run Code Online (Sandbox Code Playgroud)
Vue.component('v-input', {
  template: '#v-input-template',
  props: {
    type: {default() { return 'text'; }},
    value: {}                              // you can also add more restrictions here
  },
  name: 'v-input'
});

new Vue({
  el: '#app',
  data: {
    something: "I'm something"
  }
});
Run Code Online (Sandbox Code Playgroud)