Skip to content

Instantly share code, notes, and snippets.

@jakedohm jakedohm/LoginForm.vue
Last active Mar 22, 2019

Embed
What would you like to do?
A Vue component to handle submitting login details with Axios, instead of with a standard HTML form
<template>
<form method="post" accept-charset="UTF-8">
<label for="loginName">Username or email</label>
<input v-model="loginName" id="loginName" type="text" name="loginName" />
<label for="password">Password</label>
<input v-model="password" id="password" type="password" name="password" />
<label>
<input v-model="rememberMe" type="checkbox" name="rememberMe" />
<span>Remember me</span>
</label>
<button @click.prevent="handleLogin">Login</button>
</form>
</template>
<script>
export default {
data() {
return {
loginName: '',
password: '',
rememberMe: true,
}
},
methods: {
handleLogin() {
// Build data object
const loginData = {
loginName: this.loginName,
password: this.password,
rememberMe: this.rememberMe ? 1 : 0,
action: 'users/login',
}
// 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.
// Send the request
this.$axios
.post('/', loginData)
.then(response => {
if (response && response.data && response.data.success === true) {
// Everything worked!
alert('Logged in!')
} else if (
response &&
response.data &&
response.data.errorCode === 'invalid_credentials'
) {
// Request went through, but the submitted credentials were wrong
console.log('Invalid Credentials')
}
})
.catch(error => {
// Something went wrong with the request.
// Could've been a CSRF issue, internet connection, who knows ¯\_(ツ)_/¯
console.error('Login failed: ', error)
})
},
},
}
</script>
@jakedohm

This comment has been minimized.

Copy link
Owner Author

jakedohm commented Mar 22, 2019

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 loginData = {}

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

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
You can’t perform that action at this time.