[Vuejs]-How to use VUE router with native HTML elements as components?

3๐Ÿ‘

โœ…

I found a totally undocumented solution for making vanilla JS components with native HTML:

1 Pure HTML (no smelly injected strings):

   <div id="components" style="display:none"><!--hide component code-->
        <div id="component-category-index"><!--component 1 source code-->
            CATEGORY INDEX COMPONENT
        </div>
        <div id="component-article-show"><!--component 2 source code-->
            ARTICLE SHOW COMPONENT
        </div>
    </div>

2 vanilla JS Vue initialization:

const vue=new Vue({
    el: '#vue-app',
....your vue blabla.....
    router:new VueRouter({
        routes :[
            { path: '/article', component: { template: document.getElementById('component-article-show').outerHTML } },
            { path: '/categories', component: { template: document.getElementById('component-category-index').outerHTML } }
        ]
    })
})

pros:

  1. use vanilla JS vue with full components functionalities
  2. keep vue "style-component-logic" separated but on the same file, without
    hard breaking that clean and simple pattern

cons:

all HTML of the page must be on the same file, so this solution is OK for smaller SPA or single pages with VUE.

๐Ÿ‘คLuca C.

Leave a comment