简体   繁体   中英

VUE2 component register in Laravel

Laravel(5.8) and VUE work very nice togheter, but my app.js is getting to big.

For example, i have the following app.js:

window.Vue = require('vue');

window.Vue.component('Comp1', require('./components/Comp1.vue').default);
window.Vue.component('Comp2', require('./components/Comp2.vue').default);
window.Vue.component('Comp3', require('./components/Comp3.vue').default);

window.mainApp = new Vue({
  el: '#app'
});

In the real case, I have around 30 components + third party, witch results in a 1.2mb JS for production.

So, I'm tring to break the app.js file in many 'area related' js, just split, so I wuld have someting like:

app.js:

window.Vue = require('vue');
window.mainApp = new Vue({
  el: '#app'
});

appMainComp.js:

window.Vue.component('Comp1', require('./components/Comp1.vue').default);
window.Vue.component('Comp2', require('./components/Comp2.vue').default);

appOtherComp.js:

window.Vue.component('Comp3', require('./components/Comp3.vue').default);

Now, the catch. Everthing that I register after the app.js "window.mainApp = new Vue({ el: '#app'});"do not register.

So, is there a way to register a component after my 'mainApp' is created? Something like

mainApp.addComponent('./components/Comp1.vue');

Or any other way to break the app.js in mutiple files?

Instead of splitting up components into groups (interesting idea btw). Could you do something like this? Dynamic Imports in Vue.js

Whenever it's possible, I'd recommend to use dynamic imports to import components. They will be lazily loaded (by Webpack) when needed.

//Instead of a usual import
import MyComponent from "~/components/MyComponent.js";

//do this
const MyComponent = () => import("~/components/MyComponent.js");

You could use stacks:

Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views.

https://laravel.com/docs/6.x/blade#stacks

Parent view:

<head>
    <script src="/app.js"></script>
    @stack('loadComponent')
    <script>
        @stack('addComponent')
    </script>            
</head>

Child view:

@push('loadComponent')
    <script src="..."></script>
@endpush

@push('addComponent')
    app.addComponent(...);
@endpush

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM