Tudor Ravoiu
Tudor Ravoiu

Reputation: 2150

Vue 2 v-if not working after input changed

Maybe I'm doing it wrong but while binding v-if to two distinct input fields it only works if the input values hasn't changed.

var app = window.app = new Vue({
  el: '#admin-app',
  data() {
    return {
      language: "en"
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.common.js"></script>

<div id="admin-app">
  <select id="language" name="language" class="form-control" v-model="language">
    <option value="ro">Romanian</option>
    <option value="en">English</option>
  </select>


  <input type="text" class="form-control" value="Test RO" v-if="language == 'ro'" />
  <input type="text" class="form-control" value="Test EN" v-if="language == 'en'" />

</div>

As soon as one of the input fields has changed the v-if does not seem to work anymore. Although the "language" value changes when another option is selected.

Upvotes: 1

Views: 1807

Answers (1)

David L
David L

Reputation: 33815

VueJS appears to be extrapolating the inline input value as needing to be bound. I suspect that the input value is bound to the language prop. As a result, you can no longer safely evaluate your if condition once a value has been changed.

A workaround to this is to give both inputs explicit models via v-model. This correctly allows for both your conditional display and your input binding.

var app = window.app = new Vue({
  el: '#admin-app',
  data() {
    return {
      language: "en",
      test1: "Test RO",
      test2: "Test EN"
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.common.js"></script>

<div id="admin-app">
  <select id="language" name="language" class="form-control" v-model="language">
    <option value="ro">Romanian</option>
    <option value="en">English</option>
  </select>


  <input type="text" class="form-control" v-model="test1" v-if="language == 'ro'" />
  <input type="text" class="form-control" v-model="test2" v-if="language == 'en'" />

</div>

Upvotes: 2

Related Questions