반응형
VueJ: 컴포넌트를 탑재하기 전에 슬롯의 내용을 분석
컴포넌트가 있다고 칩시다.<my-cp :list="list"></my-cp>
이러한 템플릿의 경우:
<div class="container">
<slot></slot>
<my-cp2 v-for="li in list" :my-data="li.data"></my-cp2>
</div>
질문입니다.구성 요소를 초기화할 수 있습니까?my-cp목록 배열 또는 HTML 사용 중 어느 쪽입니까?
내 말은 두 가지 가능성을 모두 가졌다는 거야.이 경우 HTML은 다음과 같습니다.
<my-cp>
<my-cp2 my-data="foo">
<my-cp2 my-data="bar">
</my-cp>
슬롯을 장착하기 전에 슬롯의 내용을 분석하려고 합니다만, 자 컴포넌트가 이미 탑재되어 있는 경우에만 요소에 액세스 할 수 있는 것 같습니다.
기본 콘텐츠를 컴포넌트의 슬롯에 넣습니다.사용자가 슬롯 콘텐츠를 추가하면 해당 콘텐츠가 표시됩니다.그렇지 않으면 슬롯의 내용이 표시됩니다.
<div class="container">
<slot>
<my-cp2 v-for="li in list" :my-data="li.data"></my-cp2>
</slot>
</div>
여기 예가 있습니다.
편집
코멘트에서 좀 더 논의해 본 결과, 당신이 무엇을 하고 싶은지 알 수 있을 것 같습니다.미래의 독자들을 위해 명확하게 하기 위해, 제가 이해하기로는 @Nabab은 속성 또는 컴포넌트의 슬롯에 있는 HTML로 렌더링된 컴포넌트 중 하나를 사용하여 컴포넌트를 초기화할 수 있기를 원합니다.또한 컴포넌트는 기존 데이터를 수정하여 목록에 항목을 추가할 수 있어야 합니다.
렌더링 함수를 사용하여 이 작업을 수행할 수 있습니다.
Vue.component("my-cp",{
props:["list"],
data(){
return {
internalList: this.list
}
},
render(h){
let workingList = []
// Examine the default slot, and if there are any parse
// them and add the data to the workingList
if (this.$slots.default){
for (node of this.$slots.default)
// May want to check here if the node is a myCp2,
// otherwise, grab the data
workingList.push(node.componentOptions.propsData.myData)
}
// Add any items that came from the property/internal data
workingList = workingList.concat(this.internalList)
// Create a list of myCp2 vnodes with the correct data
const list = workingList.map(n => h(myCp2, {props:{myData:n}}))
// Create a button to add list items
const btn = h("button", {on:{click:() => this.internalList.push({bar: true})}}, "Add")
//Render
return h("div", [list, btn])
},
})
여기 예가 있습니다.
언급URL : https://stackoverflow.com/questions/43729014/vuejs-analyze-content-of-a-slot-with-components-before-they-are-mounted
반응형
'programing' 카테고리의 다른 글
| 동적 크기의 구조체 어레이를 작성하려면 어떻게 해야 합니까? (0) | 2022.07.05 |
|---|---|
| Vue.js에서 중첩된 속성과 함께 v-model을 사용하는 방법 (0) | 2022.07.05 |
| C에서 typedef와 typedef enum을 사용하려면 어떻게 해야 하나요? (0) | 2022.07.05 |
| 힙에 새 어레이를 생성하지 않고 Java에서 어레이 세그먼트 가져오기 (0) | 2022.07.04 |
| Java에서 네스트된 루프를 해제하려면 어떻게 해야 하나요? (0) | 2022.07.04 |