Last active
November 27, 2019 21:23
-
-
Save JamesRagonesi/2c05704c07c274af48e59371bf76e61a to your computer and use it in GitHub Desktop.
Reusable form with Vuex ORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form v-model="$v.valid" @submit.prevent="submit"> | |
<input | |
type="text" | |
v-model.trim="$v.form.text.$model" | |
@input="$v.form.text.$touch()" | |
@blur="$v.form.text.$touch()" | |
/> | |
<button @click="submit">Submit</button> | |
</form> | |
import { validationMixin } from "vuelidate"; | |
import Comment from "../models/Comment"; | |
export default { | |
name: "CommentForm", | |
mixins: [validationMixin], | |
validations: Comment.validations, | |
props: { | |
// If you need to edit a Comment then include it as a prop. Otherwise an empty object will be used to create | |
// a new Comment instance. | |
instance: { | |
type: Object, | |
default: () => {} | |
}, | |
// Quick way to distinguish if the form will be used for Editing an instance or Creating a new one | |
isEdit: { | |
type: Boolean, | |
required: true, | |
default: false | |
} | |
}, | |
data() { | |
return { | |
form: new Comment(this.instance), | |
}; | |
}, | |
methods: { | |
submit() { | |
this.$v.$touch(); | |
if (this.isEdit) { | |
// Creates a payload that can be sent via an API handler to the correct endpoint | |
this.form.toUpdatePayload(); | |
} else { | |
// Creates a payload that can be sent via an API handler to the correct endpoint | |
this.form.toCreatePayload(); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment