首页 > 解决方案 > 在 Vue.js 中单击按钮时清除文本字段?

问题描述

我有一个布局,我正在循环获取文本字段和一个按钮。我如何在按钮上添加一个功能,以便它只清除它各自的字段。在这里查看小提琴。

<div id="app">
  <h2>Each text with it's own state and clear should clear the respective 
 text fields</h2>
  <ul v-for="todo in todos">
  <li>
  <input type="text" :placeholder="`${todo.text}`">
  </li>
  <li>
  <input type="text" :placeholder="`${todo.text1}`">
  </li>
  <button>Clear</button>
  </ul>

new Vue({
  el: "#app",
  data: {
    todos: [
  { text: "Learn JavaScript", text1:"Hey" },
  { text: "Learn Vue", text1:"Hello"  },
  { text: "Play around in JSFiddle", text1:"Ciao"  },
  { text: "Build something awesome", text1:"Something"}
   ]
  }
})

标签: javascriptvue.jsvuejs2vue-componentnuxt.js

解决方案


如果要清除特定字段,可以添加一个clear将索引作为参数的方法,但在此之前,您应该向每个字段添加valuevalue1项目todo并将它们绑定到字段,如下所示:

new Vue({
  el: "#app",
  data: {
    todos: [{
        text: "Learn JavaScript",
        text1: "Hey",
        value1:'',
        value:''
          
      },
      {
        text: "Learn Vue",
        text1: "Hello",
        value1:'',
        value:''
      },
      {
        text: "Play around in JSFiddle",
        text1: "Ciao",
        value1:'',
        value:''
      },
      {
        text: "Build something awesome",
        text1: "Something",
        value1:'',
        value:''
      }
    ]
  },
  methods:{
       clear(i){
       this.todos[i].value='';
        this.todos[i].value1='';
       }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <h2>Each text with it's own state and clear should clear the respective text fields</h2>
  <ul v-for="(todo,i) in todos">
    <li>
      <input type="text" :placeholder="`${todo.text}`" v-model="todo.value">
    </li>
    <li>
      <input type="text" :placeholder="`${todo.text1}`"  v-model="todo.value1">
    </li>
    <button @click="clear(i)">Clear</button>
  </ul>
</div>


推荐阅读