feat: allow passing props and children/slots to defineClientComponent (#2198)

Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
pull/2224/head
Liberty 1 year ago committed by GitHub
parent 8ee6b905f5
commit 4c24960433
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -81,4 +81,39 @@ const ClientComp = defineClientComponent(() => {
</template> </template>
``` ```
You can also pass props/children/slots to the target component:
```vue
<script setup>
import { ref } from 'vue'
import { defineClientComponent } from 'vitepress'
const clientCompRef = ref(null)
const ClientComp = defineClientComponent(
() => import('component-that-access-window-on-import'),
// args are passed to h() - https://vuejs.org/api/render-function.html#h
[
{
ref: clientCompRef
},
{
default: () => 'default slot',
foo: () => h('div', 'foo'),
bar: () => [h('span', 'one'), h('span', 'two')]
}
],
// callback after the component is loaded, can be async
() => {
console.log(clientCompRef.value)
}
)
</script>
<template>
<ClientComp />
</template>
```
The target component will only be imported in the mounted hook of the wrapper component. The target component will only be imported in the mounted hook of the wrapper component.

@ -1,5 +1,10 @@
import { siteDataRef } from './data' import { siteDataRef } from './data'
import { inBrowser, EXTERNAL_URL_RE, sanitizeFileName } from '../shared' import {
inBrowser,
EXTERNAL_URL_RE,
sanitizeFileName,
type Awaitable
} from '../shared'
import { import {
h, h,
onMounted, onMounted,
@ -77,7 +82,11 @@ export function onContentUpdated(fn: () => any) {
}) })
} }
export function defineClientComponent(loader: AsyncComponentLoader) { export function defineClientComponent(
loader: AsyncComponentLoader,
args?: any[],
cb?: () => Awaitable<void>
) {
return { return {
setup() { setup() {
const comp = shallowRef() const comp = shallowRef()
@ -88,8 +97,9 @@ export function defineClientComponent(loader: AsyncComponentLoader) {
res = res.default res = res.default
} }
comp.value = res comp.value = res
await cb?.()
}) })
return () => (comp.value ? h(comp.value) : null) return () => (comp.value ? h(comp.value, ...(args ?? [])) : null)
} }
} }
} }

Loading…
Cancel
Save