Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically compile a component added to a template in VueJS?

I am building a blog with VueJS 2. Most of my articles are stored as Markdown files, but I want to me able to cover some more advanced topics, using features that Markdown doesn't cover. I am considering making these special posts VueJS components that would be used in a template as <article-name>, or <special-article article-title="{{articleTitle}}">. Pretty simple.

I have the component loaded already, so all I need to do is compile the template string into a real template. I might be thinking too much with my AngularJS background rather than with Vue.

I can't find any solid direction for dynamically adding a component to a template in VueJS.

like image 776
elliottregan Avatar asked Dec 11 '17 18:12

elliottregan


1 Answers

You can compile a template with Vue.compile. Just be aware it's not available in all builds. That's covered in the documentation.

Getting the data associated with it is a little more work.

console.clear()

const articles = [
  {
    title: "Testing",
    articleTemplate: "<article-title></article-title>"
  },
  {
    title: "Testing 2",
    articleTemplate: "<special-article :article-title='title'></special-article>"
  },
]

Vue.component("article-title",{
  template: `<span>Article Title</span>`
})

Vue.component("special-article", {
  props:["articleTitle"],
  template: `
    <div>
      <h1>{{articleTitle}}</h1>
      <p>Some article text</p>
    </div>
  `
})

new Vue({
  el: "#app",
  data:{
    articles
  },
  computed:{
    compiledArticles() {
      return this.articles.map(a => {
        // compile the template
        let template = Vue.compile(a.articleTemplate)
        // build a component definition object using the compile template.
        // What the data function returns is up to you depending on where 
        // the data comes from.
        return Object.assign({}, template, {data(){return a}})
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js"></script>
<div id="app">
  <component v-for="article in compiledArticles" :is="article"></component>
</div>
like image 86
Bert Avatar answered Sep 26 '22 14:09

Bert