-
-
Save philipboomy/77108c2dbcbafb7028880282ff78d5eb to your computer and use it in GitHub Desktop.
A Vue component to handle submitting account creation details with Axios, instead of with a standard HTML form
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
<template> | |
<form method="post" accept-charset="UTF-8"> | |
<h3><label for="username">Username</label></h3> | |
<input v-model="username" id="username" type="text" name="username" /> | |
<h3><label for="email">Email</label></h3> | |
<input v-model="email" id="email" type="text" name="email" /> | |
<h3><label for="password">Password</label></h3> | |
<input v-model="password" id="password" type="password" name="password" /> | |
<button @click.prevent="handleCreateAccount">Create Account</button> | |
</form> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
username: '', | |
email: '', | |
password: '', | |
} | |
}, | |
methods: { | |
handleCreateAccount() { | |
// Attempt login | |
const userData = { | |
username: this.username, | |
email: this.email, | |
password: this.password, | |
action: 'users/save-user', | |
} | |
// NOTE: The following request using this.$axios assumes that you have your CSRF | |
// header and data serialization pre-configured as recommended in my article here: | |
// https://dev.to/jakedohm_34/using-axios-with-craft-and-vue-3ceb | |
// If you don't have that set up, you'll need to manually pass your CSRF token | |
// and serialize the loginData object. See the first comment on this Gist for info. | |
this.$axios | |
.post('/', userData) | |
.then(response => { | |
if (response && response.data && response.data.success === true) { | |
// Everything worked! | |
alert('User Signed Up!') | |
} else { | |
// Request went through, but something else went wrong. | |
// Maybe the email/username was already in use, or something like that. | |
// Check the error | |
console.error('Account creation failed') | |
} | |
}) | |
.catch(error => { | |
// Something went wrong with the request. | |
// Could've been a CSRF issue, internet connection, who knows ¯\_(ツ)_/¯ | |
console.error('Account creation failed: ', error) | |
}) | |
}, | |
}, | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment