반응형
VueJS에서 템플릿에 추가된 구성 요소를 동적으로 컴파일하는 방법
나는 VueJS 2와 함께 블로그를 만들고 있다.내 기사 대부분은 마크다운 파일로 저장되어 있지만, 마크다운이 다루지 않는 기능을 사용하여 좀 더 발전된 주제를 다룰 수 있었으면 좋겠어.나는 템플릿에 사용될 VueJS 구성 요소를 다음과 같은 특수 포스트로 만드는 것을 고려하고 있다.<article-name>
또는<special-article article-title="{{articleTitle}}">
. 아주 간단하다.
구성 요소를 이미 로드했으므로 템플릿 문자열을 실제 템플릿으로 컴파일하기만 하면 된다.내 앵글과 너무 많은 생각을 하고 있을지도 몰라.부에보다는 JS 배경.
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>
반응형
'programing' 카테고리의 다른 글
모키토:유효하지 않은 UseOfMatchers예외 (0) | 2022.04.13 |
---|---|
VueJs 로컬 자산 경로 (0) | 2022.04.13 |
커밋하지 않고 상태가 Vuex에서 업데이트됨 (0) | 2022.04.13 |
vuejs 2의 watch 메서드가 isAuth 값을 업데이트하지 않음 (0) | 2022.04.13 |
소품 기능을 아동 구성 요소에 전달하고, 거기서부터 전화를 거는 방법을 Vue에서? (0) | 2022.04.12 |