0

I am in this situation:

  • old project, npm/vue compiler not available
  • using vue in vanilla JS flavour
  • using router, that needs components
  • don't want to use smelly injected strings, that are really bad for code readability

How can I use pieces of html as components for vanilla JS vue?

2
  • Maybe the title could be "How to use Vue Router with Vanilla JS", since using vanilla JS + HTML template is the first thing discussed in the docs Commented Oct 20, 2020 at 18:24
  • corrected, but the point is that the docs only states to use router with injected string templates, I'd like to avoid that approach since native html templates are better (as compiled vue does) Commented Oct 20, 2020 at 19:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.