Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ssr): render portals #714

Merged
merged 7 commits into from
Feb 15, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion packages/server-renderer/__tests__/renderToString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import {
createCommentVNode,
withScopeId,
resolveComponent,
ComponentOptions
ComponentOptions,
Portal
} from 'vue'
import { escapeHtml } from '@vue/shared'
import { renderToString, renderComponent } from '../src/renderToString'
Expand Down Expand Up @@ -379,6 +380,27 @@ describe('ssr: renderToString', () => {
})
})

test('portal', async () => {
const trueRandom = Math.random
Math.random = () => 0

expect(
await renderToString(
h(
Portal,
{
target: `#target`
},
h('span', 'hello')
)
)
).toBe(
`<!----><template id="p-0"><span>hello</span></template><script>window.addEventListener('load',()=>{document.querySelector('#target').innerHTML=document.querySelector('#p-0').innerHTML;})</script><!---->`
)

Math.random = trueRandom
})

describe('scopeId', () => {
// note: here we are only testing scopeId handling for vdom serialization.
// compiled srr render functions will include scopeId directly in strings.
Expand Down
22 changes: 21 additions & 1 deletion packages/server-renderer/src/renderToString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,27 @@ function renderVNode(
push(`<!---->`)
break
case Portal:
// TODO
if (!vnode.props || !vnode.props.target) {
console.warn(`[@vue/server-renderer] Portal doesn't have target prop`)
break
}
if (!isString(vnode.props.target)) {
console.warn(
`[@vue/server-renderer] Portal target must be a query selector`
)
break
}
const id = `p-${((Math.random() * 2 ** 64) | 0).toString(36)}` // ID of the portal
push(`<!---->`)
push(`<template id="${id}">`)
renderVNodeChildren(push, children as VNodeArrayChildren, parentComponent)
push(`</template>`)
push(
`<script>window.addEventListener('load',()=>{document.querySelector('${
vnode.props.target
}').innerHTML=document.querySelector('#${id}').innerHTML;})</script>`
)
push(`<!---->`)
break
default:
if (shapeFlag & ShapeFlags.ELEMENT) {
Expand Down