vue.jsvuejs2vuejs3v-model

In Vue why a v-model property change will reset v-binded property?


Sorry I feel like the title doesn't realy explain my question.

In the short Vue sample code below, I have 2 inputs. One uses v-bind and the other v-model.

In don't understand why when one changes the second input it resets the first input.

I know I could fixe that by using v-model for both inputs but… why? If I understood correctly v-model = v-bind+ @update so how, and once again why, a completly other property is changed.

It looks like I have the same using Vue2 or Vue3.

new Vue({
    el: '#app',
  data() {
    return {
        vBind: 'default',
        vModel: 'foo'
    };
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input :value="vBind">
  <input v-model="vModel">
</div>


Solution

  • It didn't reset the first input. What happens is that when you update the first input, you are updating it's internal state. You are not saving the state of the input, as you are not using @input event to save the input value into the component data. When you update the second input, you trigger the rerender of the template, the first input loses it's internal state and uses the value of the :value prop which is the default one.

    In short, the first input doesn't have two-way model binding. The implement it, use v-model or :value & @input attributes.

    new Vue({
        el: '#app',
      data() {
        return {
            vBind: 'default',
            vModel: 'foo'
        };
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <input :value="vBind" @input="vBind = $event.target.value"> <!-- Individual attributes binding -->
      <input v-bind="{value: vBind}" v-on="{input: event => vBind = event.target.value}"> <!-- Dynamic binding -->
      <input v-model="vModel">
    </div>