So... every time you submit a form to a Laravel backend from a Vue component you do something like...
this.busy = true;
this.$http.post('/api/salad', this.salad)
.then(response => {
this.success = true;
this.busy = false;
}).catch(errors => {
this.busy = false;
this.errors = errors.data;
}
so pretty much every component with a form in your application has this in its data property...
busy: false,
errors: null,
success: false,
and you might do it a little different as you grow the application or even worse: you have multiple forms in the same component!!!
Enter: SparkForms
If your using Laravel Spark, you have access to a javascript class located here: spark/resources/assets/js/forms/form.js
Now, your data property will look something like...
data() {
return {
saladForm: new SparkForm({name: ''})
}
}
instead of...
data() {
return {
busy: false,
errors: null,
success: false,
salad: {name: ''}
}
}
and when you submit your form (using another class provided by spark: "Spark" - with added properties located here spark/resources/assets/js/forms/http.js
) it will look like...
Spark.post('/api/salad', this.saladForm)
if your interested, you can still hook into success or failures:
Spark.post('/api/salad', this.saladForm)
.then(response => {
this.saladData = response;
});
Now, the sparkForm automatically carries the form state with it and gives you access to useful things like:
saladForm.busy
saladForm.success
saladForm.errors.hasErrors()
saladForm.errors.has('name')
saladForm.errors.get('name')
saladForm.errors.forget('name')
See spark/resources/assets/js/forms/form.js
and spark/resources/assets/js/forms/errors.js
for more available methods.
Now for the most grateful recipient of this new class: The Dom
<!-- Error Message -->
<span class="text-danger" v-if="saladForm.errors.has('name') v-text="saladForm.errors.get('name')></span>
<!-- Submit Button -->
<button type="submit" :disabled="saladForm.busy">
There you go. No more mundane form state tracking. You can thank Taylor Otwell.
- peace
I send out an email every so often about cool stuff I'm working on or launching. If you dig, go ahead and sign up!