How to compile template loaded from external api in Vue

Viewed 12309

I have a non-SPA web app that has Vue components and that works very well. However, I am looking for a way to load HTML that contains Vue via an 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?

2 Answers

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>
Related