laracasts / Vue-Forms

https://laracasts.com/series/learn-vue-2-step-by-step/episodes/19
396 stars 204 forks source link

Reset to the original data state #9

Open atorscho opened 7 years ago

atorscho commented 7 years ago

In case some of the form data properties is not an empty string (empty array, object...). This way it will really reset the form data.

mtchuenten commented 6 years ago

Nice one @atorscho . I stumbled on this issue yesterday when I wanted to update a form (student info) in an app I'm building, meaning the form comes pre-populated with previously saved data (using the v-model directive in a vue component).

Now in the middle of my editing, I realized I had also touched some fields I didn't initially intend to modify, and I didn't want to close the form, open it again and start editing from afresh. "No problem" I thought, I have my reset button, and it calls the form.reset() method; why not just click it? Oops! There's a problem after all: My form is now blank.

My first instinct was to leave the form reset() method as is (for those who may want to completely clear the form), create another one called restore() with the modification you mentioned (this[field] = this.originalData[field];), and call form.restore() instead of form.reset(). But then I realized I was giving this too much of a thought... It's actually better to just modify the form.reset() method as you did, the reason being that in the code snippet below, the reset button will always reset the form to its original data state, and that's the default html behaviour, which "I think" we are trying to replicate here.

That being said, my greatest thanks go to @JeffreyWay . That's some great abstractions you've achieved and I've been using your Form.js and Errors.js classes since I followed your tutorials on @laracasts . It took me some time to wrap my brain around them, but it was worth it and I'm reaping the benefits now. Thanks a lot.

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
    <form>
        <input type="text" name="firstname" value="Martial">
        <input type="text" name="lastname">

        <button type="reset">reset</button>
    </form>
</body>
</html>