packages/src/app/components/client-only.mjs
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) } }})
The life cycle of CSR
is different from that of SSR
. We can use these differences to achieve our purpose, that is, using the onMounted
hook will only execute this feature on the client side.
We created a tag variable
mounted
with an initial value offalse
and set it totrue
only during client-side rendering, which means that the slot content of the<ClientOnly>
component will not be rendered during server-side rendering. When rendering on the client side, the slot content of the<ClientOnly>
component will only be rendered after themounted
hook is triggered. In this way, the content wrapped by the<ClientOnly>
component will only be rendered on the client side.
In addition, the<ClientOnly>
component does not cause client activation failure, hyr, because when the client activates, the mounted hook has not yet triggered, so the server and the client render the same content, that is, nothing is rendered. After the activation is completed and the mounted hook triggers execution, the slot content of the<ClientOnly>
component will be rendered on the client side.– “Vue.js Design and Implementation”
- When
mounted === true
, that is, when the client renders, the default slot content of the<ClientOnly>
component will be rendered; - When
mounted === false
, that is, when the server renders, the fallback slot or placeholder slot or fallback Prop or placeholder Prop content of the<ClientOnly>
component will be rendered;
This article is reproduced from: https://www.wujingquan.com/posts/fb124d0f.html
This site is for inclusion only, and the copyright belongs to the original author.