清除 vuejs 表单中的输入 [英] Clearing input in vuejs form

查看:36
本文介绍了清除 vuejs 表单中的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚完成了一个 todolist 教程.提交表单时,输入字段不会清除.

Just completed a todolist tutorial. When submitting the form the input field doesn't clear.

在两者都尝试之后:

    document.getElementById("todo-field").reset();
    document.getElementById("#todo-field").value = "";

输入字段会正确清除,但也会删除待办事项.

The input field properly clears but it also deletes the todo.

好像还没来得及在todos.text数组中推送新的todo就删除了输入框.

It seems to delete the input field before it has time to push the new todo in the todos.text array.

会喜欢一些输入的家伙!谢谢!!

Would love some input guys! Thanks!!

<template>
  <form id="todo-field" v-on:submit="submitForm">
    <input type="text" v-model="text">
  </form>
     <ul>
       <li v-for="todo in todos">
        <input class="toggle" type="checkbox" v-model="todo.completed">
        <span :class="{completed: todo.completed}" class="col-md-6">
            <label @dblclick="deleteTodo(todo)">
                {{todo.text}}
            </label>
        </span>

       </li>
     </ul>

<script>
  export default {
    name: 'todos',
      data () {
        return {
          text: '',
          todos: [
          {
      text:'My Todo One',
      completed: false
    },
    {
      text:'My Todo Two',
      completed: false
    },
    {
      text:'My Todo Three',
      completed: false
    }
  ]// End of array
}
  },
    methods: {
    deleteTodo(todo){
        this.todos.splice(this.todos.indexOf(todo),1);
    },
    submitForm(e){
        this.todos.push(
            {
                text: this.text,
                completed: false
            }
        );
        //document.getElementById("todo-field").reset();
        document.getElementById("#todo-field").value = "";

        // To prevent the form from submitting
        e.preventDefault();
    }
}
}
</script>

推荐答案

您需要在 submitForm 函数中将 this.text 设置为空字符串:

What you need is to set this.text to an empty string in your submitForm function:

submitForm(e){
    this.todos.push(
        {
            text: this.text,
            completed: false
        }
    );
    this.text = "";

    // To prevent the form from submitting
    e.preventDefault();
}

记住绑定是双向的:(输入)视图可以更新(字符串)模型,或者模型可以更新视图.

Remember that binding works both ways: The (input) view can update the (string) model, or the model can update the view.

这篇关于清除 vuejs 表单中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆