connecteev's avatar

Webpack /Laravel Mix scopes get messed up - how to fix?

I have a NEW app with laravel and vue that I'm trying to get working. Thing is, webpack (laravel mix) messes up the scope in the resulting compiled app.js file.

app.js:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

const app = new Vue({
    el: '#app',
    mounted: function() {
        console.log('mounted');
    },
    methods: {
        show() {
        console.log('show');
        }
    }
});

app.show();

My welcome.blade.php file:


<!DOCTYPE html>
<html>
    <head>
        <title>Laravel</title>
    </head>
    <body>
        <div>
            <div id="app" class="content">
                <div>
                    Laravel
                </div>
            </div>
        </div>

<script src="/js/app.js"></script>
<script type="text/javascript">
    app.show();
</script>
    </body>
</html>

Calling app.show(); from the bottom of app.js file works (and I see "mounted" and "show" in the console logs), but app.show(); from the blade file results in an error in console:

Uncaught TypeError: app.show is not a function
    at (index):87

Note that using window.app.show(); in the blade file works fine.

How do I fix the webpack / laravel mix default config so that the variable scopes don't get messed up?

0 likes
6 replies
bobbybouwmann's avatar
Level 88

You always need to use window here because the javascript file and blade are both unique scopes. You either need to put everything in the app.js file or use window. AFAIK there is no other way!

connecteev's avatar

Thank you @bobbybouwmann Btw I see you on all the laracasts forum threads and on twitter...you're always helping other people out. May I ask what's your motivation for spending so much of your time helping others? Surely it's not just for the karma points :) Anyway thank you!

bobbybouwmann's avatar

@connecteev I just like helping people! I know I started once at the bottom and could use some help. I found that on YouTube sometimes, but these forums weren't really there yet!

Please or to participate in this conversation.