Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile template loaded from external api in Vue

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?

like image 910
undefinedman Avatar asked Jul 02 '17 19:07

undefinedman


People also ask

How do I get data from Vue API?

Vue Fetch data from API example To get the actual JSON body of the response, we use response. json() method. We can also access metadata such as headers , status , statusText , type , url from the Response object. The response Promise does not reject on HTTP errors (for example: 404 , 500 ).

How do I transfer data from components to Vue?

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!


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

like image 157
Bert Avatar answered Sep 18 '22 13:09

Bert