fix(ssr): properly handle ssr empty slot and fallback

This commit is contained in:
Evan You 2020-12-30 15:40:28 -05:00
parent 02493a41a0
commit 88f6b33d05

View File

@ -1,5 +1,5 @@
import { ComponentInternalInstance, Slots } from 'vue' import { ComponentInternalInstance, Slots } from 'vue'
import { Props, PushFn, renderVNodeChildren } from '../render' import { Props, PushFn, renderVNodeChildren, SSRBufferItem } from '../render'
export type SSRSlots = Record<string, SSRSlot> export type SSRSlots = Record<string, SSRSlot>
export type SSRSlot = ( export type SSRSlot = (
@ -22,18 +22,46 @@ export function ssrRenderSlot(
const slotFn = slots[slotName] const slotFn = slots[slotName]
if (slotFn) { if (slotFn) {
const scopeId = parentComponent && parentComponent.type.__scopeId const scopeId = parentComponent && parentComponent.type.__scopeId
const slotBuffer: SSRBufferItem[] = []
const bufferedPush = (item: SSRBufferItem) => {
slotBuffer.push(item)
}
const ret = slotFn( const ret = slotFn(
slotProps, slotProps,
push, bufferedPush,
parentComponent, parentComponent,
scopeId ? ` ${scopeId}-s` : `` scopeId ? ` ${scopeId}-s` : ``
) )
if (Array.isArray(ret)) { if (Array.isArray(ret)) {
// normal slot // normal slot
renderVNodeChildren(push, ret, parentComponent) renderVNodeChildren(push, ret, parentComponent)
} else {
// ssr slot.
// check if the slot renders all comments, in which case use the fallback
let isEmptySlot = true
for (let i = 0; i < slotBuffer.length; i++) {
if (!isComment(slotBuffer[i])) {
isEmptySlot = false
break
}
}
if (isEmptySlot) {
if (fallbackRenderFn) {
fallbackRenderFn()
}
} else {
for (let i = 0; i < slotBuffer.length; i++) {
push(slotBuffer[i])
}
}
} }
} else if (fallbackRenderFn) { } else if (fallbackRenderFn) {
fallbackRenderFn() fallbackRenderFn()
} }
push(`<!--]-->`) push(`<!--]-->`)
} }
const commentRE = /^<!--.*-->$/
function isComment(item: SSRBufferItem) {
return typeof item === 'string' && commentRE.test(item)
}