Import VueJs template from an external html file

0

Is there any way to import an html file into the template?

 Vue.component('porcentagens',{
data: function(){
    return {
        porcentagemSangramentoMarginal: 78,
        porcentagemPlaca: 78,
        porcentagemOLeary: 78,
    }
},
template:
    
asked by anonymous 25.09.2018 / 13:26

1 answer

1

Firstly, I believe rendering external file templates is not recommended, both for performance reasons and for security reasons.

But for learning and if it really is a necessity, I did the research and found an efficient way to do it.

  • Make an AJAX request to receive the template as a string. Ex.:

    fetch("https://meu.template.externo/template.html")
    
  • Use the Vue.compile function to compile the template into a rendering function. Ex.:

    let compiled = Vue.compile(template_externo);
    
  • Use the rendering function of the compiled template as a component rendering function.

    new Vue({
        // ...
        render: compiled.render,
        staticRenderFns: compiled.staticRenderFns,
        // ...
    });
    
  • To create a working example, I created a Gist with the following content:

    <div>
        <h1>{{ teste }}</h1>
    </div>
    

    And below is an example working:

    var template_url = "https://cdn.rawgit.com/fernandosavio/09c21e24ee23fefdd9267fa1c5650aee/raw/b2a714b18a0e46a411b1451299a9d0d173d55741/vue-teste.html";
    
    fetch(template_url)
        .then(response => response.text())
        .then(template => {
            let compiled_template = Vue.compile(template);
    
            new Vue({
              el: '#app',
              render: compiled_template.render,
              staticRenderFns: compiled_template.staticRenderFns,
              data: {
                  teste: "Olá mundo!"
              }
            });
        });
    <script src="https://cdn.jsdelivr.net/npm/vue"></script><divid="app"></div>
        
    25.09.2018 / 15:32