簡體   English   中英

如何將 v-model 綁定到包含輸入的子組件

[英]how to bind v-model to child component that contains input

我有一些看起來像這樣的組件。

<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-input 組件如下所示:

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

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

當我在輸入中輸入數據時, something不會綁定到 v-input 內部的輸入值中的任何內容。

我如何實現這一目標?

要啟用v-model ,內部組件必須采用value屬性

使用:valuevalue綁定到內部<input> ,而不是v-model (這會改變來自父級的道具)。 並且當內部<input>被編輯時,為父級發出一個input事件,以更新其值( input事件將更新父級在v-model上的變量)。

此外,如果您有type prop 的默認值,請在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可以具有的信息: 組件/使用道具傳遞數據

演示如下。

 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" } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <div id="app"> <p>Parent something: {{ something }}</p> <hr> Child: <v-input v-model="something" /> </div> <template id="v-input-template"> <input :type="type" :value="value" @input="$emit('input', $event.target.value)" class="v-input" /> </template>

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修飾符將您的值傳遞給輸入組件,以便更改將同步回父組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM