Vue组件中的Laravel CSRF字段 [英] Laravel CSRF Field in Vue Component
问题描述
我想问一下如何在vue组件中添加csrf_field().错误是
I would like to ask how can I add the csrf_field() in my vue component. The error is
属性或方法"csrfToken"未在实例上定义,但在渲染期间被引用.确保在data选项中声明反应性数据属性.
Property or method "csrfToken" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
这是代码:
<script>
export default {
name: 'create',
data: function(){
return {
msg: ''
}
},
props:['test']
}
</script>
<template>
<div id="app">
<form action="#" method="POST">
{{csrfToken()}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" id="location" class="form-control">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="number" id="age" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
</form>
</div>
</template>
推荐答案
As I already wrote here, I would simply suggest to put this in your PHP file:
<script>
window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>
</script>
通过这种方式,您可以轻松地从JS部分(在本例中为Vue)导入csrfToken.
This way you're able to easily import your csrfToken from the JS part (Vue in this case).
此外,如果将此代码插入PHP布局文件中,则由于window
是JS全局变量,因此您可以在应用程序的任何组件中使用令牌.
Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since window
is a JS global variable.
来源:我从此帖子中获得了窍门.
Source: I got the trick from this post.
这篇关于Vue组件中的Laravel CSRF字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!