Vue.js动态组件加载+热重载

时间:2016-12-04 16:54:05

标签: ecmascript-6 vue.js browserify laravel-5.3 laravel-elixir

我使用Vue.js 1.0.28

的Laravel 5.3.21应用程序

我正在使用带有browserify-hmr插件的热重新加载工作流程。

以下是用于实现此目的的简单gulpfile.js

var elixir = require('laravel-elixir');
var gutil = require('gulp-util');

require('laravel-elixir-browserify-official');
require('laravel-elixir-vueify');

//  If 'gulp watch' is run
if (gutil.env._.indexOf('watch') > -1) {

    //  Enable watchify for faster builds
    elixir.config.js.browserify.watchify.enabled = true;

    //  Add the browserify HMR plugin
    elixir.config.js.browserify.plugins.push({
        name: 'browserify-hmr',
        options: {
            url: 'http://1.2.3.4:2096',
            hostname: '1.2.3.4',
            port: 2096
        }
    })

}
elixir.config.js.browserify.watchify.options.poll = true;

elixir(function (mix) {
    mix.copy('node_modules/datatables.net-bs/css/dataTables.bootstrap.css',
             'resources/assets/css/vendor/dataTables.bootstrap.css');
    mix.styles([
        'vendor/dataTables.bootstrap.css'
    ]);
    mix.sass('app.scss');
    mix.browserify('app.js');
});

我需要从resources/assets/js/views/文件夹动态加载组件,因此我可以根据Laravel中的当前路由名$Laravel->routeName = request()->route()->getName()使我的前端代码模块化。

例如:

// Global Settings.
Route::get('admin/settings', 'Admin@settings')
    ->name('admin_global_settings');

然后在resources/assets/js/views/admin/admin_global_settings.js中我有代码来初始化Vue.js组件并将其注册到Vue.js实例:

var FeaturedOpportunities = require( '../../components/Featured-Opportunities.vue' );
window.Vue.component('FeaturedOpportunities', FeaturedOpportunities);

这很好,但这是resources/assets/js/app.js中的问题:

window.Vue = require('vue');
require('vue-resource');

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);
    next();
});

// Problem is here, have to keep track of all my routes and their corresponding modules:
var routes = {
    'organization_invites_roles': function () {
        require('./views/organization/organization_invites_roles');
    },
    'admin_global_settings': function () {
        require('./views/admin/admin_global_settings');
    },
};

// Is there a way to load it dynamically?
if (Laravel.routeName) {
    if (routes[Laravel.routeName]) {
        routes[Laravel.routeName]();
    }
}

new Vue({
    el: 'body',

    components: {

    },

    ready() {
        console.log('Vue and Vueify all set to go!');
    }
});

我找到了一些可能解决此问题的方法:Compiling dynamically required modules with Browserify但不确定这是否适用于我的情况。

0 个答案:

没有答案