programing

VueJ: 컴포넌트를 탑재하기 전에 슬롯의 내용을 분석

prostudy 2022. 7. 5. 22:03
반응형

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

반응형