Created
September 12, 2018 07:45
-
-
Save mmintel/676e9235d2107cfee85e657b003a5ce1 to your computer and use it in GitHub Desktop.
Form submission with vue
This file contains hidden or 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
<template lang="html"> | |
<div> | |
<form @submit="handleSubmit"> | |
<input | |
v-model="contactForm.name" | |
name="name" | |
type="text" | |
> | |
<input | |
v-model="contactForm.email" | |
name="email" | |
type="text" | |
> | |
<input | |
v-model="contactForm.subject" | |
name="subject" | |
type="text" | |
> | |
<textarea | |
v-model="contactForm.message" | |
name="message" | |
cols="30" | |
rows="10" | |
/> | |
<button @click="handleSubmit">Submit</button> | |
</form> | |
</div> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
contactForm: { | |
name: '', | |
email: '', | |
subject: '', | |
message: '', | |
} | |
} | |
}, | |
methods: { | |
submitToServer() { | |
return new Promise((resolve, reject) => { | |
fetch(`${process.env.functions}/mail`, { | |
method: "POST", | |
body: JSON.stringify(this.contactForm) | |
}).then(response => { | |
resolve(response); | |
}).catch(err => { | |
reject(err); | |
}); | |
}) | |
}, | |
handleSubmit() { | |
this.submitToServer().then(response => { | |
const body = response.json(); | |
if (Number(response.status) !== 200) { | |
console.log('Error submitting the form.') | |
} else { | |
console.log('Form was submitted!') | |
this.$router.push('/contact/thank-you') | |
} | |
}) | |
}, | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment