Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

javascript - Clearing input in vuejs form

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...