Vuejs 2.0 v-model conflicting with v-bind:value on different elements

Asked

Viewed 410 times

2

I have a form with some inputs that has v-model and others with v-bind:value receiving an initial value for the 'date'. Every time I type something into a v-model field it resets the value of the fields with v-bind:value to the initial value.

The error only happens in version 2.x of vuejs.

jsfiddle with an example: https://jsfiddle.net/ypeacuth/

new Vue({
  el: '#app',
  data: {
    nome: 'Ted',
    sobrenome: ''
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" id="nome" name="nome" v-model="nome">
  <input type="text" id="sobrenome" name="sobrenome" :value="sobrenome">
</div>

  • The @rnd_rss explanation is correct... When you do <input :value="sobrenome"> you’re saying the property value will always be what’s inside data.sobrenome.. And how data.sobrenome is a string empty and never modified, Vue’s behavior is to make the value one string empty whenever render component.

1 answer

1


This is really the behavior of the directives, remember that only the v-model has two way data Binding, that is if you change the input or the value that is in your date Vue keeps them 'synchronized'. Already with the :value this does not happen if you change the value of the input will not change the value on the date because it has one way data Binding, in this case the reactivity happens only from date to input. So if I understood correctly what you need it will be necessary to change the :value for v-model.

new Vue({
  el: '#app',
  data: {
    nome: 'Ted',
    sobrenome: ''
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="text" id="nome" name="nome" v-model="nome">
  <input type="text" id="sobrenome" name="sobrenome" v-model="sobrenome">
</div>

Sources: https://vuejs.org/v2/guide/forms.html#Value-Bindings

  • You can use :value to set an initial value, but it will not be possible to update the last name (the variable on the date), if you fill in something in the last name input the :value does not update the value of the input in the last name, it is always and only the last name(on date) updates the input. But if you will need to set an initial value and then this value can be updated the way is to even use the v-model

Browser other questions tagged

You are not signed in. Login or sign up in order to post.