【问题标题】:laravel out of box vuejs example not workinglaravel 开箱即用的 vuejs 示例不起作用
【发布时间】:2017-11-20 00:06:53
【问题描述】:

我只是想用 laravel 学习 vuejs,无法让示例组件正常工作。

我已经创建了一条新的路线来简单地为 vue 示例提供服务。

create.blade.php

<!DOCTYPE html>
<html>
<head>
<title>VUE</title>
</head>

<body>

<h1>example</h1>

<div id="app">

<example></example>

</div>

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

app.js 和 example.vue 文件完全一样开箱即用(所以我不会费心在这里展示 example.vue

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

我正在运行npm run watch,它似乎已经构建了应用程序文件。

控制器和路由很好,因为页面正在加载,但我收到如下控制台错误

app.js:1697 Uncaught TypeError: Cannot read property 'csrfToken' of 
undefined
at Object.<anonymous> (app.js:1697)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:778)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:41430)
at __webpack_require__ (app.js:20)
at app.js:66
at app.js:69

当我单击 chrome 中的控制台错误时,它指向 app.js 中的行:

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = 
window.Laravel.csrfToken;

它是否因为我将 csrftoken 用作刀片模板而抱怨? 我怎样才能让它在 laravel 中工作,这样我就可以玩和学习 vuejs 了?

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:

    我认为最好使用以下内容修改 bootstrap.js 文件(在 axios 导入行之后):

    window.axios.defaults.headers.common = {
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
        'X-Requested-With': 'XMLHttpRequest'
    };
    

    【讨论】:

      【解决方案2】:

      它所抱怨的代码位于resources/assets/js/bootstrap.js 源代码中,您将看到在app.js 文件的顶部引用了该代码。在您的刀片文件中,在包含 app.js 之前,您可以设置 csrf 令牌值。

      <script>
          window.Laravel.csrfToken = {{ csrf_token() }};
      </script>
      <script src="/js/app.js"></script>
      

      或者,或者,如果您只想按原样使用示例,您可能只需从bootstrap.js 中删除该行代码。但是一旦你开始更多地使用 VueJS,你以后可能会需要它。

      【讨论】:

      • 嗯,谢谢,但现在给出错误create:18 Uncaught ReferenceError: gEUrhuyDkZkWtPxbnFRY2j4ZOdxWfcccN8sGjTk2 is not defined at create:18
      • 从引导程序中删除该行,但确实有效(希望稍后将其放回)
      • 好的,我只需要{{ csrf_field() }} 没有脚本标签,感谢标记为正确:)
      • 哦,不幸的是,bootstrap.js 还没有自己构建,所以我认为上面的方法有效,但实际上并没有:(
      猜你喜欢
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      相关资源
      最近更新 更多