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!
Jun 29, 2019
6
Level 11
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?
Level 88
Please or to participate in this conversation.