Vue.js资源不能与Laravel 5.3开箱即用配置一起使用

时间:2016-12-11 01:00:30

标签: laravel vue.js laravel-5.3 node-modules vue-resource

使用包含Vue.js的Laravel 5.3全新安装并配置开箱即用:

this.$http.get(url)返回错误:

  

TypeError:此$ 1. $ http未定义

Vue.http.get(url)...替换它会产生请求,但无法发送预检选项:

  

在CORS预检频道的CORS标题“Access-Control-Allow-Headers”中丢失标记'x-csrf-token'

app.js:

require('./bootstrap');
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');

let app = new Vue({
        el: '#app',

        mounted: () => {
            navigator.geolocation.getCurrentPosition((position) => {
                app.getZip(position);
            });
        },

        methods: {
            getZip: (position) => {
                let lat = position.coords.latitude;
                let long = position.coords.longitude;
                let url = encodeURI(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&sensor=false`);
                Vue.http.get(url).then((response) => {
                    let zip = response.body.results[0].address_components[5].short_name;
                    console.log(zip);
                });
            },
        },
    });

bootstrap.js:

window._ = require('lodash');

window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');

window.Vue = require('vue');
require('vue-resource');

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});

相关的app.blade.php:

<meta id="token" name="csrf-token" content="{{ csrf_token() }}">
<script>
        window.Laravel = <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
</script>

<script src="/js/app.js"></script>

gulpfile.js:

const elixir = require('laravel-elixir');

require('laravel-elixir-vue-2');

elixir(mix => {
    mix.sass('app.scss')
       .webpack('app.js');
});

如果我包含<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.min.js"></script>,它将成功地同时发出请求:

Vue.http.get(url)
this.$http.get(url)

为什么这不适用于node_module? require('vue-resource')

1 个答案:

答案 0 :(得分:-1)

因为你正在使用require。如果你使用require,你需要一些像browserifywebpack这样的库,它允许我们使用node.js样式的模块进行编译,以便在浏览器中使用。