ell*_*gan 3 javascript vue.js vue-component vuejs2
我正在使用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}})
})
}
}
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)