source

Vue.js - 필터링된 scopedSlot에서 슬롯을 동적으로 만듭니다.

goodcode 2022. 9. 12. 11:37
반응형

Vue.js - 필터링된 scopedSlot에서 슬롯을 동적으로 만듭니다.

Vue.js 스코프드 슬롯 덕분에 Child 컴포넌트 내의 사용 가능한 모든 슬롯을 루프할 수 있습니다.템플릿의 특정 위치에 특정 문자열로 시작하는 슬롯만 렌더링하려고 합니다.

불행히도, 그것은 작동하지 않는다.제가 뭔가를 간과하고 있는 것 같아요.

Parent.vue:

<Child>
    <template #table--item.person_id="{ value }">
        <div class="text-caption">{{ value }}</div>
    </template>
</Child>

Child.vue:

<template>
    <v-data-table>
        <template v-for="(_, slotName) of tableSlots" v-slot:[slotName]="scope">
            <slot :name="slotName" v-bind="scope"></slot>
        </template>
    </v-data-table>
</template>
<script>
    export default {
        computed: {
            tableSlots() {
                const prefix = 'table--';
                const raw = this.$scopedSlots;
                const filtered = Object.keys(raw)
                    .filter(key => key.startsWith(prefix))
                    .reduce((obj, key) => ({
                        ...obj,
                        [key.replace(prefix, "")]: raw[key]
                    }), {});
                return filtered;
            }
        }
    }
</script>

https://codesandbox.io/s/keen-bose-yi8x0

부모가 다음 이름의 슬롯에 접속하려고 합니다.table--item.glutenfree그 때문에, 그 이름의 스코프 슬롯이 작성됩니다.하지만 당신이 그 대상을 정하기 위해 필터링을 할 때v-data-tableslot, 이 필터링된 이름을 자녀 슬롯에도 사용합니다.

key.replace(prefix, "")

부모가 접두사가 그대로인 이름을 대상으로 하고 있기 때문에 부모가 자식 슬롯에 액세스할 수 없습니다.

자 컴포넌트의 슬롯을 변경합니다.

<slot :name="`table--${slotName}`" v-bind="scope"></slot>

언급URL : https://stackoverflow.com/questions/65782691/vue-js-dynamically-create-slots-from-filtered-scopedslots

반응형