Clearing input in vuejs form

Tags: , ,



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

After trying both:

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

The input field properly clears but it also deletes the 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>

Answer

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.



Source: stackoverflow