簡體   English   中英

如何動態編譯添加到 VueJS 模板中的組件?

[英]How to dynamically compile a component added to a template in VueJS?

我正在使用 VueJS 2 構建博客。我的大部分文章都存儲為 Markdown 文件,但我希望能夠使用 Markdown 未涵蓋的功能來涵蓋一些更高級的主題。 我正在考慮制作這些特殊的帖子 VueJS 組件,它們將在模板中用作<article-name><special-article article-title="{{articleTitle}}"> 很簡單。

我已經加載了組件,所以我需要做的就是將模板字符串編譯成真正的模板。 我可能對我的 AngularJS 背景而不是 Vue 想得太多。

我找不到在 VueJS 中將組件動態添加到模板的任何可靠方向。

您可以使用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>

VueJS 有一個用於這種場景的內置組件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM