VUE2 component register in Laravel

老子叫甜甜 提交于 2021-02-08 23:50:24

问题


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?


回答1:


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");



回答2:


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



来源:https://stackoverflow.com/questions/60376054/vue2-component-register-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!