首页 文章

如何在VueJS中动态编译添加到模板的组件?

提问于
浏览
2

我正在使用VueJS 2构建博客 . 我的大多数文章都存储为Markdown文件,但我希望能够使用Markdown未涵盖的功能来介绍一些更高级的主题 . 我正在考虑将这些特殊帖子的VueJS组件用作模板 <article-name><special-article article-title="{{articleTitle}}"> . 很简单 .

我已经加载了组件,所以我需要做的就是将模板字符串编译成一个真实的模板 . 我可能会用AngularJS背景而不是Vue来思考太多 .

我找不到任何可靠的方向来动态地将组件添加到VueJS中的模板中 .

2 回答

  • 0

    您可以使用Vue.compile编译模板 . 请注意文档中涵盖的's not available in all builds. That' .

    获取与之相关的数据是一项更多的工作 .

    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>
    
  • 5

    VueJS有一个用于此场景的内置组件:

    <component is="article-component-name"></component>

相关问题