gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:19:06 24 4
gpt4 key购买 nike

我正在使用 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>

关于javascript - 如何动态编译添加到 VueJS 模板中的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com