Skip to content

Instantly share code, notes, and snippets.

@maninak
Last active January 22, 2022 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maninak/72a3836498a13541e866b5d3999e2841 to your computer and use it in GitHub Desktop.
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.
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