Created
November 15, 2018 14:59
-
-
Save calebporzio/ae2d46ce2f270d2764a79fa4822a2c80 to your computer and use it in GitHub Desktop.
A Vue component to include Laravel's CSRF Token within form tag
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
// Usage: | |
// <vue-form method="PUT"> | |
// <input type="text" name="email"> | |
// <input type="submit"> | |
// </vue-form> | |
<template> | |
<form :method="method.toUpperCase() == 'GET' ? 'GET' : 'POST'"> | |
<input-hidden :value="csrfToken" name="_token"/> | |
<input-hidden | |
v-if="['GET', 'POST'].indexOf(method.toUpperCase()) === -1" | |
:value="method" | |
name="_method" | |
/> | |
<!-- | |
This hidden submit button accomplishes 2 things: | |
1: Allows the user to hit "enter" while an input field is focused to submit the form. | |
2: Allows a mobile user to hit "Go" in the on-screen keyboard to submit the form. | |
--> | |
<input type="submit" class="absolute invisible z-0"> | |
<slot/> | |
</form> | |
</template> | |
<script> | |
export default { | |
props: { method: { default: 'POST' }}, | |
data() { return { csrfToken: null }}, | |
created() { | |
this.csrfToken = document.querySelector('meta[name="csrf-token"]').content | |
}, | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should use
mounted()
and notcreated()
to ensure the DOM is available.