DEV Community

vue.js modules in the browser, the cheap way

Magnus Manske on April 05, 2018

I really enjoy vue.js, and prefer it to React et al. One advantage of vue is the ability to use it in the browser directly, without having to pre-p...
Collapse
 
ycmjason profile image
YCM Jason

Interesting idea! Thank you for sharing this.

Just a few JS advice. (You might lose a little bit of browser support, but since you are using object method shorthand, it shouldn't support IE and safari already according to MDN.)

  1. Don't use var anymore. Use const and let instead.
  2. Don't use me = this, use arrow function to have the context inherited.
  3. Use promise instead of callback. (Eliminate the use of counter by using Promise.all)
  4. Avoid jquery
  5. Use either
{
    f: function(){
        ...
    }
}

Or

{
    f(){
        ...
    }
}

Not both. Although they are essentially the same thing, it is important to have consistency.

Collapse
 
magnusmanske profile image
Magnus Manske • Edited

Thanks! This is what it looks like in proper ES6 (some parts omitted):

let vue_components = {
    loadComponents : function ( components ) {
        return Promise.all ( components.map ( component => this.loadComponent(component) ) ) ;
    } ,
    loadComponent ( component ) {
        let id = this.getComponentID ( component ) ;
        if ( $('#'+id).length > 0 ) return Promise.resolve(42) ; // Already loaded/loading
        $('body').append($("
").attr({id:id}).css({display:'none'})); return fetch ( this.getComponentURL(component) ) .then ( (response) => response.text() ) .then ( (html) => $('#'+id).html(html) ) } }

I tried to get rid of jQuery, but document.getElementById("content").innerHTML = html doesn't seem to work for some reason, even though it does set the HTML. But I need jQuery for the larger project anyway, so that's OK...

Collapse
 
rhymes profile image
rhymes

You could probably replace jQuery with fetch but you lose IE (Edge works).

If IE is a requirement and since you don't need to do anything fancy you could try using a library like nanoajax so you can replace jQuery with that.