Skip to content

Instantly share code, notes, and snippets.

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

What would you like to do?
A Vue component to handle submitting login details with Axios, instead of with a standard HTML form
<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" />
<input v-model="rememberMe" type="checkbox" name="rememberMe" />
<span>Remember me</span>
<button @click.prevent="handleLogin">Login</button>
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:
// 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
.post('/', loginData)
.then(response => {
if (response && && === true) {
// Everything worked!
alert('Logged in!')
} else if (
response && && === '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)

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:

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'/', 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.