【问题标题】:The global variable is not working with VueJS & Laravel全局变量不适用于 VueJS 和 Laravel
【发布时间】:2021-02-04 17:39:05
【问题描述】:

我在 app.blade.php 中有一个像这样的全局变量>

<script>
window.App = {!! json_encode([
    'apiToken' => Auth::user()->api_token,
]) !!};
</script>

我在 app.blade.php 布局中有一个

它有:

 <script>
  export default {
    created() {
        this.getRol();
    },
    methods: {
        getRol() {
            console.log(App.apiToken);
            axios.get('/api/user?api_token='+App.apiToken)
            .then(response => {
                console.log(response);
                this.rol_id = response.data.data.rol_id;
            });
        }
    }
  }
  </script>

但我想知道为什么它会说这个错误?

[Vue 警告]:创建钩子时出错:“ReferenceError: App is not defined”

它是全局创建的。

谢谢

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:

    要创建要在 Vue 中使用的“全局变量”,请在此处查看 LinusBorg 在 Vue 论坛上的回答:https://forum.vuejs.org/t/global-variable-for-vue-project/32510/4

    帖子内容:

    在项目中使用 tru 全局变量来保持全局命名空间干净并不是一个好主意。

    相反,创建一个小文件,您可以从中导出需要在许多地方使用的任何变量:

    // variables.js
    export const myVar = 'This is my variable'
    export const settings = {
      some: 'Settings'
    }
    
    // in your Vue
    import { myVar, Settings } from './variables.js'
    

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 1970-01-01
      • 2017-01-08
      • 2018-08-06
      • 2017-11-28
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多