Skip to content

Commit

Permalink
feat: allow passing props and children/slots to defineClientComponent (
Browse files Browse the repository at this point in the history
…#2198)

Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
  • Loading branch information
Liberty-liu and brc-dd committed Apr 15, 2023
1 parent 8ee6b90 commit 4c24960
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
35 changes: 35 additions & 0 deletions docs/guide/ssr-compat.md
Expand Up @@ -81,4 +81,39 @@ const ClientComp = defineClientComponent(() => {
</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.
16 changes: 13 additions & 3 deletions src/client/app/utils.ts
@@ -1,5 +1,10 @@
import { siteDataRef } from './data'
import { inBrowser, EXTERNAL_URL_RE, sanitizeFileName } from '../shared'
import {
inBrowser,
EXTERNAL_URL_RE,
sanitizeFileName,
type Awaitable
} from '../shared'
import {
h,
onMounted,
Expand Down Expand Up @@ -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 {
setup() {
const comp = shallowRef()
Expand All @@ -88,8 +97,9 @@ export function defineClientComponent(loader: AsyncComponentLoader) {
res = res.default
}
comp.value = res
await cb?.()
})
return () => (comp.value ? h(comp.value) : null)
return () => (comp.value ? h(comp.value, ...(args ?? [])) : null)
}
}
}

0 comments on commit 4c24960

Please sign in to comment.