Add beforeNuxtRender hook

This commit is contained in:
Sebastien Chopin 2017-07-27 16:26:59 +02:00
parent 6c6e6e55aa
commit 4a6b651d56
3 changed files with 23 additions and 16 deletions

View File

@ -113,6 +113,7 @@ async function createApp (ssrContext) {
<% if(store) { %>store,<% } %> <% if(store) { %>store,<% } %>
req: ssrContext ? ssrContext.req : undefined, req: ssrContext ? ssrContext.req : undefined,
res: ssrContext ? ssrContext.res : undefined, res: ssrContext ? ssrContext.res : undefined,
beforeRenderFns: ssrContext ? ssrContext.beforeRenderFns : undefined
}, app) }, app)
<% plugins.filter(p => p.ssr).forEach(plugin => { %> <% plugins.filter(p => p.ssr).forEach(plugin => { %>

View File

@ -45,6 +45,7 @@ export default async context => {
// Create context.next for simulate next() of beforeEach() when wanted to redirect // Create context.next for simulate next() of beforeEach() when wanted to redirect
context.redirected = false context.redirected = false
context.next = createNext(context) context.next = createNext(context)
context.beforeRenderFns = []
const { app, router<%= (store ? ', store' : '') %> } = await createApp(context) const { app, router<%= (store ? ', store' : '') %> } = await createApp(context)
const _app = new Vue(app) const _app = new Vue(app)
@ -210,6 +211,8 @@ export default async context => {
context.nuxt.state = store.state context.nuxt.state = store.state
<% } %> <% } %>
await Promise.all(context.beforeRenderFns.map((fn) => promisify(fn, { Components, nuxtState: context.nuxt })))
// If no error, return main app // If no error, return main app
if (!context.nuxt.error) { if (!context.nuxt.error) {
return _app return _app

View File

@ -104,6 +104,9 @@ export function getContext (context, app) {
if (context.req) ctx.req = context.req if (context.req) ctx.req = context.req
if (context.res) ctx.res = context.res if (context.res) ctx.res = context.res
if (context.from) ctx.from = context.from if (context.from) ctx.from = context.from
if (ctx.isServer && context.beforeRenderFns) {
ctx.beforeNuxtRender = (fn) => context.beforeRenderFns.push(fn)
}
return ctx return ctx
} }