-
Notifications
You must be signed in to change notification settings - Fork 258
/
compileSlots.ts
46 lines (42 loc) · 1.21 KB
/
compileSlots.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { compile } from '@vue/compiler-dom'
import * as vue from 'vue'
import type { SetupContext } from 'vue'
export function processSlot(source = '', Vue = vue) {
let template = source.trim()
const hasWrappingTemplate = template && template.startsWith('<template')
// allow content without `template` tag, for easier testing
if (!hasWrappingTemplate) {
template = `<template #default="params">${template}</template>`
}
const { code } = compile(
`<SlotWrapper v-bind="$attrs">${template}</SlotWrapper>`,
{
mode: 'function',
prefixIdentifiers: __USE_PREFIX_IDENTIFIERS__
}
)
const createRenderFunction = new Function(
'Vue',
__BROWSER__ ? `'use strict';\n${code}` : code
)
return {
inheritAttrs: false,
render: createRenderFunction(Vue),
components: {
SlotWrapper: {
inheritAttrs: false,
setup(_: Record<string, any>, ctx: SetupContext) {
return () => {
const names = Object.keys(ctx.slots)
if (names.length === 0) {
return []
} else {
const slotName = names[0]
return ctx.slots[slotName]!(ctx.attrs)
}
}
}
}
}
}
}