How to compile template loaded from external api in Vue

11,004

Solution 1

There is a compile function available in Vue that compiles templates to render functions. Using the compiled functions requires a little more detail than you have provided (if you needed to use the returned template with data, for example), but here is one example.

console.clear()

Vue.component("my-component",{
  template: `<h1>My Component</h1>`
})

const template = `
<div>
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
</div>
`

new Vue({
  el: "#app",
  data:{
    compiled: null
  },
  mounted(){
    setTimeout(() => {
      this.compiled = Vue.compile(template)
    }, 500)
    
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
  <component :is="compiled"></component>
</div>

Note that in the example, I wrapped your example template in a div tag. Vue requires that there is on a single root element for a Vue or component.

Solution 2

After many hours, I managed to pass some properties to the component to be compiled.

In the HTML body:

<!-- some where in the HTML body -->
<div id="vCard2">
   <component :is="compiled"></component>
</div>

<script>
var vmCard2 = new Vue({
  el: '#vCard2',
  data: {
    compiled: null,
    status: ''
  },
  methods: {
    show: function () {
      // macro is some dynamic string content or html template that contains mustache
      var macro = this.status == 'some_switch' ? '...{{payment.status}}...' : '...{{refund.status}}...';
      Vue.component('cp-macro', {
        data: function () {
          return {
            payment: vmCard1.payment,
            refund: vmCard1.refund
          }
        },
        template: '<span>'+macro+'</span>'
      })
      this.compiled = Vue.compile('<cp-macro></cp-macro>');
    },
    hide: function () {
      this.compiled = null; // must remove for the next macro to show
    }
  }
})
</script>
Share:
11,004

Related videos on Youtube

undefinedman
Author by

undefinedman

Updated on September 16, 2022

Comments

  • undefinedman
    undefinedman over 1 year

    I have an non SPA web app that has Vue components and that works very good. However, I am looking for a way to load HTML that contains Vue via external API.

    So, I simply make a call to /ajax/dialogbox/client/add which is returning HTML containing Vue components, like:

    <h1>Add client</h1>
    <div>My static content</div>
    <my-component></my-component>
    

    but obviously <my-component></my-component> does not do anything. In Angular 1 I was using $compile service to compile the HTML before output.

    Is there a way to do the same in Vue?

  • Philipp Mochine
    Philipp Mochine about 6 years
    how do you pass Props?
  • Bert
    Bert about 6 years
    @PhilippMochine Easiest way is to add them to <component :myprop="someValue" />.