PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to compile template loaded from external api in Vue

 October 17, 2022     compilation, vue-component, vue.js     No comments   

Issue

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?


Solution

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.



Answered By - Bert
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing