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

前端 未结 1 443
小鲜肉
小鲜肉 2021-02-11 02:10

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

1条回答
  •  有刺的猬
    2021-02-11 02:29

    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: ""
      },
      {
        title: "Testing 2",
        articleTemplate: ""
      },
    ]
    
    Vue.component("article-title",{
      template: `Article Title`
    })
    
    Vue.component("special-article", {
      props:["articleTitle"],
      template: `
        

    {{articleTitle}}

    Some article text

    ` }) 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}}) }) } } })
    
    

    0 讨论(0)
提交回复
热议问题