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

8ftvxx2r  于 2022-12-08  发布在  Babel
关注(0)|答案(2)|浏览(192)

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

<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: ''
    }
  }
}

该v输入分量如下所示:

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

<script>
export default {
    props: ['type'],
    name: 'v-input'
}
</script>

当我把数据输入到输入中时,something不会绑定到v-input内部的输入值中的任何内容。
我该如何做到这一点?

epggiuax

epggiuax1#

若要启用v-model的使用,内部元件必须接受value属性。
使用:value而不是v-modelvalue绑定到内部的<input>(这将使来自父对象的属性发生变化)。当内部的<input>被编辑时,为父对象发出input事件,以更新其值(input事件将更新父对象在v-model上的变量)。
此外,如果您有type属性的预设值,请在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>

有关props可以具有的内容的信息:组件/使用属性传递数据。
演示如下。
第一次

ukdjmx9f

ukdjmx9f2#

https://v2.vuejs.org/v2/guide/components.html#sync-Modifier

<template>
  <q-layout>
    <v-input :value.sync="something" />
  </q-layout>
</template>

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

<script>
export default {
    props: ['type', 'value'],
    name: 'v-input',
    data:function(){
        return {
            inputVal: ''
        };
    },
    watch:{
        value: function(newValue){
            this.$emit('update:value', newValue)
        }
    }
}
</script>

您需要使用.sync修饰符将值传递给输入组件,以便更改将同步回父组件。

相关问题