laravel-mix 升级后应用程序不再看到全局变量

After laravel-mix upgrade app no longer sees global vars

我正在将一个项目从 laravel-mix v2.0 升级到 v4.0,我现在看到一个问题,在运行时我的组件无法像以前那样看到全局范围的变量.升级构建工具如何影响运行时?

我知道我可以添加 instance properties to the vue prototype,但这真的是我需要采取的方法吗?看起来它应该仍然能够像以前一样读取全局变量。

html

<script type="text/javascript">
    var games = [
       // a bunch of objects
    ];
</script>
<script src="{{ mix('js/app.js') }}"></script>

app.js

import ChannelSubscriptionSlider from './components/guild-subscriptions/ChannelSubscriptionSlider.vue';
Vue.component('channel-subscription-slider', ChannelSubscriptionSlider);

ChannelSubscriptionSlider.vue

import Vue from 'vue';
import VueResource from 'vue-resource';
Vue.use(VueResource);
export default {
    data: function () {
        return {
            games: games, // undefined when used within this component, but used to work before upgrade
        }
    },

编辑 2

使用 `window.games,这会 "register" 你的全局变量。


尽管我所做的是以下内容,但请考虑 MPA 而不是 SPA:

在app.js中我只留下以下几行:

require('./bootstrap');

window.Vue = require('vue');

在我制作的名为 main.js 的单独文件中,我将其作为示例:

import Sidebar from './components/layouts/Sidebar.vue'
import Topnav from './components/layouts/Topnav.vue'

new Vue({
  el: '#sidebar',
  render: h => h(Sidebar)
});

new Vue({
  el: '#topnav',
  render: h => h(Topnav)
});

在 app.blade.php 的末尾我输入:

<script src="{{ asset('js/app.js') }}"></script>

<script type="text/javascript">
    const user_props = {
        fullName : {!! json_encode(Auth::user()->fullName) !!},
        username : {!! json_encode(Auth::user()->username) !!},
    }

    user_props.install = function(){
      Object.defineProperty(Vue.prototype, '$userProps', {
        get () { return user_props }
      })
    }

    Vue.use(user_props);
</script>

<script src="{{ asset('js/main.js') }}"></script>

这是有效的,因为我在 app.js 中安装了 vue,但是在我声明并安装原型后加载了使用 user_props 的组件...此外,由于 vue 是在 [=56= 中安装的] 加载后我可以使用 Vue.use(user_props);...

并且忘了在 webpack.mix.js 中添加 main.js:

 mix.js('resources/js/app.js',          'public/js')
    .sass('resources/sass/app.scss',    'public/css')

    .js('resources/js/main.js',        'public/js/')

编辑 1

根据您的评论和文档:https://vuejs.org/v2/cookbook/adding-instance-properties.html#The-Importance-of-Scoping-Instance-Properties

$只是一个约定:

... We scope instance properties with $ to avoid this. You can even use your own convention if you’d like, such as $_appName or ΩappName, to prevent even conflicts with plugins or future features.

考虑到这一点,您可以将其设置为:

Vue.prototype.games = games;

然后您可以在每个组件上访问它作为 this.games

如文档所示,执行此操作时必须小心,不要覆盖它。因此,如果您在 Vue 组件的数据部分声明了它,我认为您应该删除这些行...