2022-08-02 15:05:02 +00:00
|
|
|
import { ref, onMounted, defineComponent, createElementBlock, h, Fragment } from 'vue'
|
2021-11-15 11:57:38 +00:00
|
|
|
|
|
|
|
export default defineComponent({
|
|
|
|
name: 'ClientOnly',
|
|
|
|
// eslint-disable-next-line vue/require-prop-types
|
|
|
|
props: ['fallback', 'placeholder', 'placeholderTag', 'fallbackTag'],
|
|
|
|
setup (_, { slots }) {
|
|
|
|
const mounted = ref(false)
|
|
|
|
onMounted(() => { mounted.value = true })
|
|
|
|
return (props) => {
|
|
|
|
if (mounted.value) { return slots.default?.() }
|
|
|
|
const slot = slots.fallback || slots.placeholder
|
|
|
|
if (slot) { return slot() }
|
|
|
|
const fallbackStr = props.fallback || props.placeholder || ''
|
|
|
|
const fallbackTag = props.fallbackTag || props.placeholderTag || 'span'
|
|
|
|
return createElementBlock(fallbackTag, null, fallbackStr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2022-04-19 19:13:55 +00:00
|
|
|
|
|
|
|
export function createClientOnly (component) {
|
2022-08-02 15:05:02 +00:00
|
|
|
const { setup, render: _render, template: _template } = component
|
|
|
|
if (_render) {
|
|
|
|
// override the component render (non <script setup> component)
|
|
|
|
component.render = (ctx, ...args) => {
|
|
|
|
return ctx.mounted$
|
|
|
|
? h(Fragment, null, [h(_render(ctx, ...args), ctx.$attrs ?? ctx._.attrs)])
|
|
|
|
: h('div', ctx.$attrs ?? ctx._.attrs)
|
|
|
|
}
|
|
|
|
} else if (_template) {
|
|
|
|
// handle runtime-compiler template
|
|
|
|
component.template = `
|
|
|
|
<template v-if="mounted$">${_template}</template>
|
|
|
|
<template v-else><div></div></template>
|
|
|
|
`
|
|
|
|
}
|
2022-04-19 19:13:55 +00:00
|
|
|
return defineComponent({
|
2022-08-02 15:05:02 +00:00
|
|
|
...component,
|
|
|
|
setup (props, ctx) {
|
|
|
|
const mounted$ = ref(false)
|
|
|
|
onMounted(() => { mounted$.value = true })
|
|
|
|
|
|
|
|
return Promise.resolve(setup?.(props, ctx) || {})
|
|
|
|
.then((setupState) => {
|
|
|
|
return typeof setupState !== 'function'
|
|
|
|
? { ...setupState, mounted$ }
|
|
|
|
: () => {
|
|
|
|
return mounted$.value
|
|
|
|
// use Fragment to avoid oldChildren is null issue
|
|
|
|
? h(Fragment, null, [h(setupState(props, ctx), ctx.attrs)])
|
|
|
|
: h('div', ctx.attrs)
|
|
|
|
}
|
|
|
|
})
|
2022-04-19 19:13:55 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|