如何在vuejs组件中使用laravel csrf标记

时间:2017-06-14 12:49:29

标签: javascript php laravel vue.js

我正在尝试在vue组件中使用表单。问题是它不接受我的csrf令牌。我尝试使用

以多种方式添加它
{{!! csrf_field()!!}} // the component does not render after this

然后我尝试添加xcsrf

blade.php


>meta name="csrf-token" content="{{ csrf_token() }}">

然后将其添加到脚本

 $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
}); //this gives error token mismatch

然后我尝试将xcsrf添加到mount函数中,如此

mounted() {
        this.csrf = window.laravel.csrfToken        
    } // I get the error csrfToken of undefined

这是我的代码 的 app.js

//new vue component 
Vue.component('search', require('./components/Searchnames.vue'));

component.vue

<template>
    <div class="row">
        <form class="col-md-12" action='/table' method="POST">

        <input type="hidden" name="_token" :value="csrf">
            <h1 class="mainheading">
                I have found the following names matching your search
            </h1>
            <br/>
            <br/>
            <br/>
            <div class='names_container' v-for="name in names">
                <button class=" btn-default btn-block glow-border names" type='submit' v-on:click="getName">
                {{name.label.eng}}
                </button>

            </div>

        </form>
    </div>

</template>


<script>
  export default {
        data: function () {
            return {
                names: [],
                selected: "",
                csrf: ""
            };

        },
        methods: {
            getData: function () {
                let self = this;
                self.$http.jsonp(url, {
                        jsonpCallback: "JSON_CALLBACK"
                    })
                    .then(response => {
                        response.body.map(function (obj) {
                            if (obj.type == 'org') {
                                self.names.push(obj)
                            }

                        });
                        console.log(JSON.stringify(this.names))
                    })
            },
            getName: function (element) {
                this.selected = element.target.innerText
            }
        },
        mounted: function () {
            this.csrf = window.laravel.csrfToken ;
            this.getData();


        }
    }
</script>

blade.php模板

@section('content')
     <div>
         <search></search>
         </div>   
    @endsection

    <script>
        var url = '{{ $url }}'.replace(/&amp;/g, '&');
    </script>

1 个答案:

答案 0 :(得分:2)

试试这个

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

然后尝试这个或将其添加到app.blade.php标题:

for (int i = 0; i < checkBoxes.length; i++){
    if(!checkBoxes[i].isChecked()){
        n = 3;
    }
}
return n;