Last active
January 22, 2022 18:13
-
-
Save maninak/72a3836498a13541e866b5d3999e2841 to your computer and use it in GitHub Desktop.
A composable to modify/change attributes/props (e.g. `class` or `style`) of slotted elements when using v-slot in vue.js [wip]. Only to be used in render (aka `h()`) functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { SetupFunction } from '@nuxtjs/composition-api' | |
import type { CreateElement, VNode } from 'vue' | |
function useModifiedSlot( | |
slotName: string, | |
dataToAppend: Required<Parameters<CreateElement>>['1'], | |
) { | |
const slot = getCurrentInstance()?.slots[slotName] | |
const slotVnode = Array.isArray(slot) && slot[0].data | |
if (slotVnode) { | |
slotVnode.staticClass = `${slotVnode.staticClass ?? ''} ${dataToAppend.staticClass ?? ''}` | |
// TODO: maninak implement assigning all other fields and extract function to standalone file in /composables | |
} else { | |
throw new Error( | |
"Reached no man's land inside `useModifiedSlot()`. Maybe this use case isn't covered by the implementation..?", | |
) | |
} | |
// Type assertion necessary due to error in original typings for `getCurrentInstance`. `Array.isArray(slot)` too. | |
return slot as VNode[] | undefined | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment