Created
March 17, 2019 14:41
-
-
Save kevinruscoe/7dfd81d51c975156b50a717908cba891 to your computer and use it in GitHub Desktop.
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> | |
<a | |
v-on:click.prevent="submit()" | |
v-bind:href="href" | |
v-bind:class="classes"> | |
<slot></slot> | |
</a> | |
</template> | |
<script> | |
export default { | |
props: ['confirm', 'classes', 'href', 'method', 'csrf'], | |
methods: { | |
submit() { | |
if (this.confirm) { | |
if(! confirm(this.confirm)) { | |
return; | |
} | |
} | |
this.method = ! this.method ? "PUT" : this.method; | |
this.method = this.method.toUpperCase(); | |
if(! ['PUT', 'DELETE', 'PATCH', 'POST'].includes(this.method)) { | |
return; | |
} | |
if (! this.csrf) { | |
var token = document.head.querySelector('meta[name="csrf-token"]'); | |
if (token) { | |
this.csrf = token.content; | |
} | |
} | |
this.buildAndSubmitForm(); | |
}, | |
buildAndSubmitForm() { | |
var form = document.createElement('form'); | |
form.setAttribute('method', 'POST'); | |
form.setAttribute('action', this.href); | |
var inputToken = document.createElement('input'); | |
inputToken.setAttribute('type', 'hidden'); | |
inputToken.setAttribute('name', '_token'); | |
inputToken.setAttribute('value', this.csrf); | |
var inputMethod = document.createElement('input'); | |
inputMethod.setAttribute('type', 'hidden'); | |
inputMethod.setAttribute('name', '_method'); | |
inputMethod.setAttribute('value', this.method); | |
form.appendChild(inputToken) | |
form.appendChild(inputMethod) | |
document.body.appendChild(form) | |
form.submit(); | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment