【问题标题】:How to dynamically compile a component added to a template in VueJS?如何动态编译添加到 VueJS 模板中的组件?
【发布时间】:2018-05-25 08:27:48
【问题描述】:

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

我已经加载了组件,所以我需要做的就是将模板字符串编译成真正的模板。我可能对我的 AngularJS 背景而不是 Vue 想得太多。

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

【问题讨论】:

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

您可以使用Vue.compile 编译模板。请注意,它并非在所有版本中都可用。文档中对此进行了介绍。

获取与之关联的数据需要更多的工作。

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>

【讨论】:

  • 谢谢! &lt;component&gt; 组件实际上是我现在所需要的。将来,我只会在需要时加载特殊文章列表,但现在很容易将它们与网站的其余部分捆绑在一起。
【解决方案2】:

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

&lt;component is="article-component-name"&gt;&lt;/component&gt;

【讨论】:

猜你喜欢
  • 2019-05-23
  • 2020-07-22
  • 2016-05-19
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2014-11-23
  • 2023-03-06
相关资源
最近更新 更多