2017-12-11 3 views
1

VueJS 2로 블로그를 만들고 있습니다. 대부분의 기사가 Markdown 파일로 저장되어 있지만 Markdown에서 다루지 않는 기능을 사용하여 좀 더 고급 주제를 다룰 수 있기를 바랍니다. 템플릿으로 <article-name> 또는 <special-article article-title="{{articleTitle}}">과 같은 특수 게시물 VueJS 구성 요소를 만드는 것을 고려하고 있습니다. 아주 간단합니다.VueJS에서 템플릿에 추가 된 구성 요소를 동적으로 컴파일하는 방법은 무엇입니까?

이미로드 된 구성 요소가 있으므로 템플릿 문자열을 실제 템플릿으로 컴파일해야합니다. 나는 Vue보다는 AngularJS 배경을 너무 많이 생각할 수도 있습니다.

VueJS에서 동적으로 템플릿에 구성 요소를 추가하는 방향을 찾을 수 없습니다.

+0

이 필요합니까? https://vuejs.org/v2/guide/components.html#Dynamic-Components –

+1

@KresimirPendic yup! 그 해결책은 내가 필요로했던 것보다 더 복잡했다. 더 간단한 해결책에 대한 다른 대답을 확인하십시오. – elliottregan

답변

3

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>

+0

감사! ''구성 요소는 사실 내가 지금 필요한 모든 것입니다. 앞으로는 필요한 경우에만 특수 기사 목록을로드 하겠지만 현재는 나머지 사이트와 함께 묶을 수 있습니다. – elliottregan

0

VueJS 내장 부품이 시나리오에 대한했습니다

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

관련 문제