Add nuxtServerInit action in the store

This commit is contained in:
Sébastien Chopin 2016-11-17 13:52:00 +01:00
parent 2677afb46f
commit c9250b4d07
2 changed files with 39 additions and 28 deletions

View File

@ -49,6 +49,14 @@ export default context => {
context.error = _app.error.bind(_app) context.error = _app.error.bind(_app)
<%= (isDev ? 'const s = isDev && Date.now()' : '') %> <%= (isDev ? 'const s = isDev && Date.now()' : '') %>
<% if (store) { %>
let promise = (store._actions && store._actions.nuxtServerInit ? store.dispatch('nuxtServerInit', pick(getContext(context), 'req', 'res', 'params', 'query')) : null)
if (!(promise instanceof Promise)) promise = Promise.resolve()
<% } else { %>
let promise = Promise.resolve()
<% } %>
return promise
.then(() => {
// Call data & fecth hooks on components matched by the route. // Call data & fecth hooks on components matched by the route.
let Components = getMatchedComponents(context.route) let Components = getMatchedComponents(context.route)
if (!Components.length) { if (!Components.length) {
@ -58,25 +66,28 @@ export default context => {
} }
return Promise.all(Components.map((Component) => { return Promise.all(Components.map((Component) => {
let promises = [] let promises = []
if (Component.data && typeof Component.data === 'function') { if (!Component.options) {
Component._data = Component.data Component = Vue.extend(Component)
var promise = Component.data(getContext(context)) Component._Ctor = Component
}
if (Component.options.data && typeof Component.options.data === 'function') {
Component._data = Component.options.data
var promise = Component._data(getContext(context))
if (!(promise instanceof Promise)) promise = Promise.resolve(promise) if (!(promise instanceof Promise)) promise = Promise.resolve(promise)
promise.then((data) => { promise.then((data) => {
Component.data = () => data Component.options.data = () => data
if (Component._Ctor) { Component._Ctor.options.data = Component.options.data
Component._Ctor = Vue.extend(Component)
}
}) })
promises.push(promise) promises.push(promise)
} else { } else {
promises.push(null) promises.push(null)
} }
if (Component.fetch) { if (Component.options.fetch) {
promises.push(Component.fetch(getContext(context))) promises.push(Component.options.fetch(getContext(context)))
} }
return Promise.all(promises) return Promise.all(promises)
})) }))
})
.then((res) => { .then((res) => {
<% if (isDev) { %> <% if (isDev) { %>
debug('Data fetching ' + context.req.url + ': ' + (Date.now() - s) + 'ms') debug('Data fetching ' + context.req.url + ': ' + (Date.now() - s) + 'ms')

View File

@ -1,6 +1,6 @@
{ {
"name": "nuxt", "name": "nuxt",
"version": "0.4.4", "version": "0.4.5",
"description": "A minimalistic framework for server-rendered Vue.js applications (inspired by Next.js)", "description": "A minimalistic framework for server-rendered Vue.js applications (inspired by Next.js)",
"main": "index.js", "main": "index.js",
"license": "MIT", "license": "MIT",