Skip to content

Instantly share code, notes, and snippets.

@jakedohm
Created March 27, 2019 15:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jakedohm/612fc39390bc8c8ef4632542544713cb to your computer and use it in GitHub Desktop.
Save jakedohm/612fc39390bc8c8ef4632542544713cb 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
<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>
@jakedohm
Copy link
Author

As mentioned in the code, the way the form is submitted in this Gist requires you to pre-configure Axios according to this guide: https://dev.to/jakedohm_34/using-axios-with-craft-and-vue-3ceb

If you haven't configured Axios to handle CSRF and serialization automatically, the following code should work as a replacement:

import { stringify } from 'qs'
import axios from 'axios'

// see Gist for login data object
const userData = {}

loginData[window.csrfTokenName] = window.csrfTokenValue
axios.post('/', stringify(userData))

The rest (the code above and below the Axios call) should work the same for both implementations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment