代码之家  ›  专栏  ›  技术社区  ›  Ben

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

  •  1
  • Ben  · 技术社区  · 7 年前

    我正在将一个项目从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
            }
        },
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Erubiel    7 年前

    编辑2

    使用`window.games,这将“注册”全局变量。


    虽然,我所做的是以下,考虑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安装在app.js中,因此我可以使用 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

    这个 $ 这只是一个惯例:

    ... 我们使用$scope实例属性来避免这种情况。如果愿意,您甚至可以使用自己的约定,例如$\u appName或appName,以防止与插件或将来的功能发生冲突。

    Vue.prototype.games = games;
    

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

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

    推荐文章