IT이야기

범위 지정 슬롯에서 refs 요소를 가져오는 방법

cyworld 2022. 6. 1. 17:38
반응형

범위 지정 슬롯에서 refs 요소를 가져오는 방법

슬롯 템플릿에 참조가 있는 경우 컴포넌트에서 참조에 액세스하려면 어떻게 해야 합니까?예를 들어 다음과 같습니다.

v-component.표시하다

<template>
    <div>
        <slot></slot>
    </div>
</template>
<script>
   export default {
       created() {
           console.log(this.$refs.ele)
       }
   }
</script>

app.vue

<template>
    <v-component>
       <template slot-scope="props">
          <h1 ref="ele"></h1>
       </template>
    </v-component>
</template>
<script>
   import VComponent from './v-component
   export default {
       components: { VComponent }
   }
</script>

v-computent의 이.$refs.ele.vue 출력이 정의되지 않았습니다.문제는 이 요소를 어떻게 얻을 수 있느냐는 것입니다.

명명된 각 요소slot그리고.scopedSlot가지다context.$refs. 객체가 존재하는지 확인하는 것을 잊지 마십시오.

<template>
    <v-component>
        <template slot-scope="props">
            <h1 ref="ele">{{ props }}</h1>
        </template>
    </v-component>
</template>
<script>
import VComponent from './v-component'
export default {
    components: { VComponent }
}
</script>

그리고.

<template>
    <div>
        <slot demo="foo"></slot>
    </div>
</template>
<script>
export default {
    created() {
        this.$nextTick(function() { // lazy
            console.warn(this.$scopedSlots.default()[0].context.$refs)
        });
    }
}
</script>

결과:

결과

이는 Vue 개발자에 의해 좋지 않은 아이디어로 간주됩니다.https://github.com/vuejs/vue/issues/7661

근데 Vue3에서는el에 의해 취득된 슬롯의 엔트리

this.$refs.myRef.$slots['my-slot']().el

항상 null입니다(예:appContext)

Vue 2에서는 마운트된 상태에서 이 작업을 수행할 수 있습니다.

  mounted() {
    console.log(this.$slots)
  },

보다 정확하게

당신은 이걸 할 수 있다.

  mounted() {
    console.log(this.$slots.name_of_your_slot)
  },

언급URL : https://stackoverflow.com/questions/52440368/how-to-get-refs-element-in-scoped-slot

반응형