Vue.js Vue 组件中的 v-bind 和 v-model 绑定问题



我在表单输入字段中使用了v-bindv-model。 但是当我运行npm run dev命令时,它会显示: v-bind:value="user.name" conflicts with v-model on the same element because the latter already expands to a value binding internally error .

v-bind中,我绑定了我的props值,v-model使用局部变量。

这是我的代码示例:

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

v-model="username"只是以下各项的简写: :value="username" @input="username = $event"

因此,您有:

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

这是错误 - Vue 不知道输入的内容

作为一般规则,v-bind:valuev-model冲突,因为它也绑定到value。该规则的例外情况是复选框和单选按钮,其中两者都有效(并且可能是您获得想法的地方)。在这些情况下,v-model实际上绑定到selected属性。

<!-- 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" />

您不能同时将两个不同的数据源(即 v-bind 和 v 模型)绑定到同一输入;如果你想初始化来自 props 的输入,你可以使用 this.user.name 设置数据 prop username,而无需使用 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:''
  }
}