[Vuejs]-Reset component data on click (Without $vm.forceUpdate())

0👍

In your case there is no need to re-render the vue Component, which is what forceUpdate() will be doing forcefully. I will suggest using an object for modeling your form, lets say, formModel. For Example:

Template:

    <form id="app" @submit="checkForm" method="post" novalidate="true">
        <label for="name">Name</label>
        <input type="text" name="name" id="name" v-model="formModel.name">
        <label for="email">Email</label>
        <input type="email" name="email" id="email" v-model="formModel.email">
        <input type="submit" value="Submit">
    </form>
    <<ul>
        <li v-for="error in errors">{{ error }}</li>
    </ul>

JS:

   let app = new Vue({
        el: "#app",
        data: {
            errors: [],
            formModel: {}
        },
        methods: {
            checkForm: function(e) {
                let self = this
                self.errors = []
                if (!self.formModel.name) {
                    self.errors.push("Name required.")
                }
                if (!self.formModel.email) {
                    self.errors.push("Email required.")
                } else if (!self.validEmail(self.formModel.email)) {
                    self.errors.push("Valid email required.")
                }
                if (!self.errors.length) {
                    self.initializeForm()
                };
                e.preventDefault()
            },
            validEmail: function(email) {
                let re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
                return re.test(email)
            },
            initializeForm(){
                self.formModel = {}
            }
        }
    });

In this manner no matter how many input elements you have in your component you will just need to set the main model object.

Leave a comment