Skip to content

feat: add access to context from serverPrefetch (fix #9447) #9591

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

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 4 additions & 4 deletions src/server/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@ const normalizeRender = vm => {
}
}

function waitForServerPrefetch (vm, resolve, reject) {
function waitForServerPrefetch (vm, resolve, reject, ssrContext) {
let handlers = vm.$options.serverPrefetch
if (isDef(handlers)) {
if (!Array.isArray(handlers)) handlers = [handlers]
try {
const promises = []
for (let i = 0, j = handlers.length; i < j; i++) {
const result = handlers[i].call(vm, vm)
const result = handlers[i].call(vm, ssrContext)
if (result && typeof result.then === 'function') {
promises.push(result)
}
Expand Down Expand Up @@ -206,7 +206,7 @@ function renderComponentInner (node, isRoot, context) {

const reject = context.done

waitForServerPrefetch(child, resolve, reject)
waitForServerPrefetch(child, resolve, reject, context)
}

function renderAsyncComponent (node, isRoot, context) {
Expand Down Expand Up @@ -432,6 +432,6 @@ export function createRenderFunction (
const resolve = () => {
renderNode(component._render(), true, context)
}
waitForServerPrefetch(component, resolve, done)
waitForServerPrefetch(component, resolve, done, context)
}
}
26 changes: 24 additions & 2 deletions test/ssr/ssr-string.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1334,6 +1334,28 @@ describe('SSR: renderToString', () => {
})
})

it('should pass $ssrContext to serverPrefetch option', done => {
renderVmWithOptions({
template: `
<div>{{ ctx }}</div>
`,
data: {
count: 0
},
serverPrefetch (ctx) {
return new Promise((resolve) => {
setTimeout(() => {
this.ctx = ctx.userContext.foo
resolve()
}, 1)
})
}
}, result => {
expect(result).toContain('<div data-server-rendered="true">bar</div>')
done()
}, { foo: 'bar' })
})

it('should support serverPrefetch option (nested)', done => {
renderVmWithOptions({
template: `
Expand Down Expand Up @@ -1543,8 +1565,8 @@ describe('SSR: renderToString', () => {
})
})

function renderVmWithOptions (options, cb) {
renderToString(new Vue(options), (err, res) => {
function renderVmWithOptions (options, cb, ctx = {}) {
renderToString(new Vue(options), ctx, (err, res) => {
expect(err).toBeNull()
cb(res)
})
Expand Down