How to Compile Template Loaded from External Api in Vue

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

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=""></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.

8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest