简体   繁体   中英

Vue.js v-bind & v-model binding issue in Vue component

I've use v-bind and v-model in my form input field. but when i run npm run dev command it's show the: v-bind:value="user.name" conflicts with v-model on the same element because the latter already expands to a value binding internally error .

in v-bind i'm bind my props value and in v-model use a local variable.

Here is my Code Sample:

<label>Name</label>
      <input name="name" class="form-control" v-bind:value="user.name" v-model="username"/>
 props:{

  user:{
    type:[Array,Object],
    required:true,
  },

},
data(){
  return{

   username:'',
   email:'',
   id:''
  }
},

You can't have two different data sources (ie v-bind and v-model at the same time) bind to the same input; If you are looking to initialize the input from props, you can set the data prop username with this.user.name without using v-bind:value :

<input name="name" class="form-control" v-model="username"/>
 props:{

  user:{
    type:[Array,Object],
    required:true,
  },

},
data(){
  return{

   username: this.user.name,
   email:'',
   id:''
  }
}

v-model="username" is just a shorthand for: :value="username" @input="username = $event"

and as a result you have:

<input
  name="name"
  class="form-control"
  :value="user.name"
  :value="username"
  @input="username = $event"
/>

it is error - vue don't know what put into input

As a general rule v-bind:value conflicts with v-model because it also binds to value . The exceptions to that rule are check boxes and radio buttons where having both is valid (and may be where you got the idea from). In those cases v-model actually binds to the selected property.

<!-- Valid, binds to selected -->
<input type="checkbox" name="fruits" :value="currentFruit" v-model="selectedFruits" />
<input type="radio" name="animal" :value="currentAnimal" v-model="selectedAnimal" />

<!-- Not valid, both bind to value -->
<input type="text" :value="currentName" v-model-"currentName" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM