如何与Vue交换输入字段?

click当事件触发时,我很难交换字段。下面是我的代码,它只是更改了一次值和名称,但如果再次单击它就不起作用。它也不会改变该v-model值。有人可以帮我吗?


超文本标记语言


<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>

代码查看:


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';

      }

   }

});


智慧大石
浏览 111回答 1
1回答

繁华开满天机

从绑定中删除括号,并从输入中删除除和[ ]之外的所有属性:typev-model<button @click="swapInputFields">Swap</button><input type="text" v-model="fromCity"><br><input type="text" v-model="toCity">您只需要这些模型变量fromCity和toCity数据:data() {&nbsp; &nbsp;return {&nbsp; &nbsp; &nbsp; fromCity:'FROM',&nbsp; &nbsp; &nbsp; toCity :'TO'&nbsp; &nbsp;}},并像这样交换它们:swapInputFields(){&nbsp; &nbsp;const temp = this.fromCity;&nbsp; &nbsp;this.fromCity = this.toCity;&nbsp; &nbsp;this.toCity = temp;}这是一个演示:new Vue({&nbsp; el: "#app",&nbsp; data(){&nbsp; &nbsp; &nbsp;return {&nbsp; &nbsp; &nbsp; &nbsp; fromCity:'FROM',&nbsp; &nbsp; &nbsp; &nbsp; toCity :'TO'&nbsp; &nbsp; &nbsp;}&nbsp; },&nbsp; methods: {&nbsp; &nbsp; swapInputFields()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; const temp = this.fromCity;&nbsp; &nbsp; &nbsp; this.fromCity = this.toCity;&nbsp; &nbsp; &nbsp; this.toCity = temp;&nbsp; &nbsp; }&nbsp; }});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="app">&nbsp; <button @click="swapInputFields">Swap</button>&nbsp; <input type="text" v-model="fromCity"><br>&nbsp; <input type="text" v-model="toCity"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript