[Vuejs]-How to clear input fields after adding a new element?

0👍

I don’t know vue, but you can always select all inputs and set it’s value on ” :
document.querySelectorAll('input').forEach(input => input.value='')

in best case apply it to container so sth like that:

document.querySelector('.formClassName').querySelectorAll('input').forEach(input => input.value='')

0👍

Just use following:

deleteStudent(studId) {
  this.stud.splice(students.id, 1)
}

You can splice something based on it’s id the 1 after the comma is that it deletes 1 stud-data from your id.

0👍

When you want to use a v-model on your form and let the user enter some data, you should pass an initial object to your inputs. And when the user submits the form, you’ll push that data to your array, following to reset your initial object.

So this implementation will help you:

<!-- add new student -->
<br>
    <input v-model="initialState.name" placeholder="surname">
    <select v-model="initialState.group">
            <option value="1">1</option>
            <option value="2">2</option>
    </select>
    <input v-model="initialState.year" placeholder="Bitrh year">
    <input type="checkbox" v-model="initialState.done">
    <label>done</label>
    <input v-model.number="initialState.mark" type="number" placeholder="mark">
    <button type="reset" @click="addStudent()">add to array</button>
</div>
<!-- /add new student -->

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="/index.js"></script>
var app = new Vue ({
    el: '#app',
    data: {
        students: [],
        initialState: {
          id: '',
          name: '',
          group: '',
          year: '',
          done: true,
          mark: 0
        },
        search: '',
    },
    methods: {
        deleteStudent(studId) {
            this.students = this.students.filter(elem => {
                return elem.id != studId;
            });
        },
        addStudent() {
            const id = this.students.length + 1;
            this.students.push({ id, this.initialState });
            this.initialState = JSON.parse(JSON.stringify({
              id: '',
              name: '',
              group: '',
              year: '',
              done: true,
              mark: 0
            }));
        }
    }
})

Leave a comment