Clearing input in vuejs form

2020-02-26 00:29发布

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>

5条回答
Summer. ? 凉城
2楼-- · 2020-02-26 00:49

Assuming that you have a form that is huge or simply you do not want to reset each form field one by one, you can reset all the fields of the form by iterating through the fields one by one

var self = this;
Object.keys(this.data.form).forEach(function(key,index) {
    self.data.form[key] = '';
});

The above will reset all fields of the given this.data.form object to empty string. Let's say there are one or two fields that you selectively want to set to a specific value in that case inside the above block you can easily put a condition based on field name

if(key === "country") 
   self.data.form[key] = 'Canada';
else 
   self.data.form[key] = ''; 

Or if you want to reset the field based on type and you have boolean and other field types in that case

if(typeof self.data.form[key] === "string") 
   self.data.form[key] = ''; 
else if (typeof self.data.form[key] === "boolean") 
   self.data.form[key] = false; 

For more type info see here

A basic vuejs template and script sample would look as follow

<template>
  <div>
    <form @submit.prevent="onSubmit">
      <input type="text" class="input" placeholder="User first name" v-model="data.form.firstName">
      <input type="text" class="input" placeholder="User last name" v-model="data.form.lastName">
      <input type="text" class="input" placeholder="User phone" v-model="data.form.phone">
      <input type="submit" class="button is-info" value="Add">
      <input type="button" class="button is-warning" @click="resetForm()" value="Reset Form">
    </form>
  </div>
</template>

See ow the @submit.prevent="onSubmit" is used in the form element. That would by default, prevent the form submission and call the onSubmit function.

Let's assume we have the following for the above

<script>
  export default {
    data() {
      return {
        data: {
          form: {
            firstName: '',
            lastName: '',
            phone: ''
          }
        }
      }
    },
    methods: {
      onSubmit: function() {
        console.log('Make API request.')
        this.resetForm(); //clear form automatically after successful request
      },
      resetForm() {
        console.log('Reseting the form')
        var self = this; //you need this because *this* will refer to Object.keys below`

        //Iterate through each object field, key is name of the object field`
        Object.keys(this.data.form).forEach(function(key,index) {
          self.data.form[key] = '';
        });
      }
    }
  }
</script>

You can call the resetForm from anywhere and it will reset your form fields.

查看更多
我只想做你的唯一
3楼-- · 2020-02-26 00:49

This solution is only for components

If we toggle(show/hide) components using booleans then data is also removed. No need to clean the form fields.

I usually make components and initialize them using booleans. e.g.

<template>
    <button @click="show_create_form = true">Add New Record</button
    <create-form v-if="show_create_form" />
</template>


<script>
...
data(){
   return{
       show_create_form:false //making it false by default
   }
},
methods:{
    submitForm(){
      //...
      this.axios.post('/submit-form-url',data,config)
           .then((response) => {
               this.show_create_form= false; //hide it again after success.
               //if you now click on add new record button then it will show you empty form
           }).catch((error) => {
              //
           })
    }
}
...
</script>

When use clicks on edit button then this boolean becomes true and after successful submit I change it to false again.

查看更多
4楼-- · 2020-02-26 00:55

For reset all field in one form you can use event.target.reset()

const app = new Vue({
    el: '#app',    
    data(){
	return{        
            name : null,
	    lastname : null,
	    address : null
	}
    },
    methods: {
        submitForm : function(event){
            event.preventDefault(),
            //process...             
            event.target.reset()
        }
    }

});
form input[type=text]{border-radius:5px; padding:6px; border:1px solid #ddd}
form input[type=submit]{border-radius:5px; padding:8px; background:#060; color:#fff; cursor:pointer; border:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="app">
<form id="todo-field" v-on:submit="submitForm">
        <input type="text" v-model="name"><br><br>
        <input type="text" v-model="lastname"><br><br>
        <input type="text" v-model="address"><br><br>
        <input type="submit" value="Send"><br>
    </form>
</div>

查看更多
Bombasti
5楼-- · 2020-02-26 00:57

Markup

<template lang="pug">
  form
    input.input(type='text', v-model='formData.firstName')
    input.input(type='text', v-model='formData.lastName')
    button(@click='resetForm', value='Reset Form') Reset Form
</template>

Script

<script>
  const initFromData = { firstName: '', lastName: '' };

  export default {
    data() {
      return {
        formData: Object.assign({}, initFromData),
      };
    },
    methods: {
      resetForm() {
        // if shallow copy
        this.formData = Object.assign({}, initFromData);

        // if deep copy
        // this.formData = JSON.parse(JSON.stringify(this.initFromData));
      },
    },
  };
</script>

Read the difference between a deep copy and a shallow copy HERE.

查看更多
干净又极端
6楼-- · 2020-02-26 00:58

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.

查看更多
登录 后发表回答