在按钮上清除文本字段单击Vue Js?

时间:2019-01-16 17:08:42

标签: vue.js vuetify.js nuxt.js

我有一个布局,可以循环获取文本字段和按钮。如何在按钮上添加功能,以便仅清除其相应字段。 在这里查看小提琴。

 https://jsfiddle.net/pu4ht2gb/7/

<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"}
   ]
  }
})

2 个答案:

答案 0 :(得分:1)

您确实应该浏览https://vuejs.org/v2/上的文档

您缺少实现目标的许多基本构造函数。首先,您需要将click事件添加到您的按钮中。 (https://vuejs.org/v2/guide/events.html

接下来,您需要在渲染(https://vuejs.org/v2/guide/list.html)时参考待办事项的索引

您可以在此处创建一个名为clear的简单方法:

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"}
    ]
  },
  methods: {
    clear (index) {
      // Allows for unlimited keys
      for (let key in this.todos[index]) {
        this.$set(this.todos[index], key, null);
      }
    }
  }
})

请注意,在清除方法中,我通过使用$ set方法(https://vuejs.org/v2/api/#vm-set)并引用传递的索引来确保反应性。

最后,我使用Vue的v模型将输入值绑定到todo模型,我可以获得额外的信用吗? (https://vuejs.org/v2/api/#v-model

完整代码: https://jsfiddle.net/cdsgu62L/10/

答案 1 :(得分:1)

如果您要清除特定字段,则可以添加方法clear,该方法以索引为参数,但是在此之前,您应该为每个{{1}添加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='';
       }
  }
})