undefinedman
undefinedman

Reputation: 670

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?

Upvotes: 9

Views: 15652

Answers (3)

svifty7
svifty7

Reputation: 31

I use this method in my project for rendering templates as reactive component. All I need is passing in props URL for download template or template for immediate render:

<div id="app"></div>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const { createApp, defineComponent, markRaw } = Vue;
 
  createApp({
    template: `
      <component v-if="component" :is="component"/>
      <span v-else>Component is loading...</span>
    `,
    data: () => {
      return {
        component: undefined
      }
    },
    provide: {
      message: 'Hello Vue!'
    },
    mounted() {
      setTimeout(async () => {
        this.component = await this.defineRawComponent('<span>{{ message }}</span>')
      }, 1000);
    },
    methods: {
      async defineRawComponent(template, url) {
        if (!template && !url) {
            throw new Error('URL and template is not defined');
        }

        try {
            let html = template;

            if (!html) {
                const { data } = await axios.get(url);

                html = data;
            }

            return Promise.resolve(
              markRaw(
                defineComponent({
                  name: 'RawContent',
                  template: html,
                  inject: ['message']
                })
              )
            );
        } catch (err) {
            return Promise.reject(err);
        }
      }
    }
  }).mount('#app')
</script>

Upvotes: 0

Bert
Bert

Reputation: 82489

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.

Upvotes: 15

kiatng
kiatng

Reputation: 3057

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>

Upvotes: 3

Related Questions