How to swap input fields with Vue?

Viewed 437

I am having difficulty to swap fields when a click event is triggered. Here is my code below, which is just changing the value and name once but it does not work if I click again. It also does not change the v-model value. Can anyone help me please?

HTML

<div id='app'>
      
  <button @click="swapInputFields">Swap</button>
  <input type="text" :name="[field1]" v-model="model1" :value="[fromCity]"><br>
  <input type="text" :name="[field2]" v-model="model2" :value="[toCity]">

</div>

Vue code:

var app = new Vue({
   el: '#app',
   data: {
      fromCity:'FROM',
      toCity :'TO',
      field1 :'name1',
      field2 :'name2'
   },
   methods: {
      swapInputFields()
      {
         this.fromCity = 'TO';
         this.toCity ='FROM';
         this.field1 = 'name2';
         this.field2 ='name1';
      }
   }
});
1 Answers

Remove the [ ] brackets from the bindings and remove all of the attributes from the inputs other than type and v-model:

<button @click="swapInputFields">Swap</button>
<input type="text" v-model="fromCity"><br>
<input type="text" v-model="toCity">

You only need those model variables fromCity and toCity in your data:

data() {
   return {
      fromCity:'FROM',
      toCity :'TO'
   }
},

And swap them like this:

swapInputFields()
{
   const temp = this.fromCity;
   this.fromCity = this.toCity;
   this.toCity = temp;
}

Here is a demo:

new Vue({
  el: "#app",
  data(){
     return {
        fromCity:'FROM',
        toCity :'TO'
     }
  },
  methods: {
    swapInputFields()
    {
      const temp = this.fromCity;
      this.fromCity = this.toCity;
      this.toCity = temp;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="swapInputFields">Swap</button>
  <input type="text" v-model="fromCity"><br>
  <input type="text" v-model="toCity">
</div>

Related