mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-11 08:33:53 +00:00
Merge branch 'dev' of github.com:Atinux/nuxt.js into dev
Conflicts: lib/app/client.js lib/app/server.js
This commit is contained in:
commit
a870896c67
@ -1,32 +1,61 @@
|
||||
'use strict'
|
||||
|
||||
import Vue from 'vue'
|
||||
import middleware from './middleware'
|
||||
import { createApp, NuxtError } from './index'
|
||||
import { applyAsyncData, sanitizeComponent, getMatchedComponents, getMatchedComponentsInstances, flatMapComponents, getContext, middlewareSeries, promisify, getLocation, compile } from './utils'
|
||||
import {
|
||||
applyAsyncData,
|
||||
sanitizeComponent,
|
||||
getMatchedComponents,
|
||||
getMatchedComponentsInstances,
|
||||
flatMapComponents,
|
||||
getContext,
|
||||
middlewareSeries,
|
||||
promisify,
|
||||
getLocation,
|
||||
compile
|
||||
} from './utils'
|
||||
|
||||
const noopData = () => { return {} }
|
||||
const noopFetch = () => {}
|
||||
|
||||
// Global shared references
|
||||
let _lastPaths = []
|
||||
let _lastComponentsFiles = []
|
||||
|
||||
let app
|
||||
let router
|
||||
<%= (store ? 'let store' : '') %>
|
||||
<% if (store) { %>let store<% } %>
|
||||
|
||||
// Try to rehydrate SSR data from window
|
||||
const NUXT = window.__NUXT__ || {}
|
||||
NUXT.components = window.__COMPONENTS__ || null
|
||||
|
||||
// Create and mount App
|
||||
createApp()
|
||||
.then(mountApp)
|
||||
.catch(err => {
|
||||
console.error('[nuxt] Error while initializing app', err)
|
||||
})
|
||||
|
||||
function componentOption(component, key, ...args) {
|
||||
if (!component || !component.options || !component.options[key]) {
|
||||
return {}
|
||||
}
|
||||
const option = component.options[key]
|
||||
if (typeof option === 'function') {
|
||||
return option(...args)
|
||||
}
|
||||
return option
|
||||
}
|
||||
|
||||
function mapTransitions(Components, to, from) {
|
||||
const componentTransitions = (component) => {
|
||||
if (!component || !component.options || !component.options.transition) {
|
||||
return {}
|
||||
}
|
||||
let transition = component.options.transition
|
||||
if (typeof transition === 'function') {
|
||||
transition = transition(to, from)
|
||||
}
|
||||
const componentTransitions = component => {
|
||||
const transition = componentOption(component, 'transition', to, from)
|
||||
return (typeof transition === 'string' ? { name: transition } : transition)
|
||||
}
|
||||
return Components.map((Component) => {
|
||||
|
||||
return Components.map(Component => {
|
||||
// Clone original object to prevent overrides
|
||||
const transitions = Object.assign({}, componentTransitions(Component))
|
||||
|
||||
// Combine transitions & prefer `leave` transitions of 'from' route
|
||||
if (from && from.matched.length && from.matched[0].components.default) {
|
||||
const from_transitions = componentTransitions(from.matched[0].components.default)
|
||||
@ -34,167 +63,253 @@ function mapTransitions(Components, to, from) {
|
||||
.filter(key => from_transitions[key] && key.toLowerCase().indexOf('leave') !== -1)
|
||||
.forEach(key => { transitions[key] = from_transitions[key] })
|
||||
}
|
||||
|
||||
return transitions
|
||||
})
|
||||
}
|
||||
|
||||
function loadAsyncComponents (to, from, next) {
|
||||
const resolveComponents = flatMapComponents(to, (Component, _, match, key) => {
|
||||
if (typeof Component === 'function' && !Component.options) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const _resolve = (Component) => {
|
||||
Component = sanitizeComponent(Component)
|
||||
match.components[key] = Component
|
||||
resolve(Component)
|
||||
}
|
||||
Component().then(_resolve).catch(reject)
|
||||
})
|
||||
}
|
||||
Component = sanitizeComponent(Component)
|
||||
match.components[key] = Component
|
||||
return match.components[key]
|
||||
})
|
||||
async function loadAsyncComponents (to, from, next) {
|
||||
// Check if route hash changed
|
||||
const fromPath = from.fullPath.split('#')[0]
|
||||
const toPath = to.fullPath.split('#')[0]
|
||||
this._hashChanged = (fromPath === toPath)
|
||||
if (!this._hashChanged) {
|
||||
<%= (loading ? 'this.$loading.start && this.$loading.start()' : '') %>
|
||||
this._hashChanged = fromPath === toPath
|
||||
|
||||
<% if (loading) { %>
|
||||
if (!this._hashChanged && this.$loading.start) {
|
||||
this.$loading.start()
|
||||
}
|
||||
Promise.all(resolveComponents)
|
||||
.then(() => next())
|
||||
.catch((err) => {
|
||||
let statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500
|
||||
this.error({ statusCode, message: err.message })
|
||||
next(false)
|
||||
<% } %>
|
||||
|
||||
try {
|
||||
await Promise.all(flatMapComponents(to, (Component, _, match, key) => {
|
||||
// If component already resolved
|
||||
if (typeof Component !== 'function' || Component.options) {
|
||||
const _Component = sanitizeComponent(Component)
|
||||
match.components[key] = _Component
|
||||
return _Component
|
||||
}
|
||||
|
||||
// Resolve component
|
||||
return Component().then(Component => {
|
||||
const _Component = sanitizeComponent(Component)
|
||||
match.components[key] = _Component
|
||||
return _Component
|
||||
})
|
||||
}))
|
||||
|
||||
next()
|
||||
} catch (err) {
|
||||
if (!err) err = {}
|
||||
const statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500
|
||||
this.error({ statusCode, message: err.message })
|
||||
next(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Get matched components
|
||||
function resolveComponents(router) {
|
||||
const path = getLocation(router.options.base)
|
||||
|
||||
return flatMapComponents(router.match(path), (Component, _, match, key, index) => {
|
||||
// If component already resolved
|
||||
if (typeof Component !== 'function' || Component.options) {
|
||||
const _Component = sanitizeComponent(Component)
|
||||
match.components[key] = _Component
|
||||
return _Component
|
||||
}
|
||||
|
||||
// Resolve component
|
||||
return Component().then(Component => {
|
||||
const _Component = sanitizeComponent(Component)
|
||||
if (NUXT.serverRendered) {
|
||||
applyAsyncData(_Component, NUXT.data[index])
|
||||
if (NUXT.components) {
|
||||
Component.options.components = Object.assign(_Component.options.components, NUXT.components[index])
|
||||
}
|
||||
_Component._Ctor = _Component
|
||||
}
|
||||
match.components[key] = _Component
|
||||
return _Component
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function callMiddleware (Components, context, layout) {
|
||||
// if layout is undefined, only call global middleware
|
||||
let midd = <%= serialize(router.middleware, { isJSON: true }) %>
|
||||
let unknownMiddleware = false
|
||||
|
||||
// If layout is undefined, only call global middleware
|
||||
if (typeof layout !== 'undefined') {
|
||||
midd = [] // exclude global middleware if layout defined (already called before)
|
||||
midd = [] // Exclude global middleware if layout defined (already called before)
|
||||
if (layout.middleware) {
|
||||
midd = midd.concat(layout.middleware)
|
||||
}
|
||||
Components.forEach((Component) => {
|
||||
Components.forEach(Component => {
|
||||
if (Component.options.middleware) {
|
||||
midd = midd.concat(Component.options.middleware)
|
||||
}
|
||||
})
|
||||
}
|
||||
midd = midd.map((name) => {
|
||||
|
||||
midd = midd.map(name => {
|
||||
if (typeof middleware[name] !== 'function') {
|
||||
unknownMiddleware = true
|
||||
this.error({ statusCode: 500, message: 'Unknown middleware ' + name })
|
||||
}
|
||||
return middleware[name]
|
||||
})
|
||||
if (unknownMiddleware) return
|
||||
|
||||
if (unknownMiddleware) return
|
||||
return middlewareSeries(midd, context)
|
||||
}
|
||||
|
||||
async function render (to, from, next) {
|
||||
if (this._hashChanged) return next()
|
||||
let layout
|
||||
|
||||
// nextCalled is true when redirected
|
||||
let nextCalled = false
|
||||
const _next = function (path) {
|
||||
<%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
|
||||
const _next = path => {
|
||||
<% if(loading) { %>if(this.$loading.finish) this.$loading.finish()<% } %>
|
||||
if (nextCalled) return
|
||||
nextCalled = true
|
||||
next(path)
|
||||
}
|
||||
let context = getContext({ to<%= (store ? ', store' : '') %>, isClient: true, next: _next.bind(this), error: this.error.bind(this) }, app)
|
||||
let Components = getMatchedComponents(to)
|
||||
|
||||
// Update context
|
||||
const context = getContext({
|
||||
to,
|
||||
<% if (store) { %>store,<% } %>
|
||||
isClient: true,
|
||||
next: _next.bind(this),
|
||||
error: this.error.bind(this),
|
||||
app
|
||||
})
|
||||
this._context = context
|
||||
this._dateLastError = this.$options._nuxt.dateErr
|
||||
this._hadError = !!this.$options._nuxt.err
|
||||
|
||||
// Get route's matched components
|
||||
const Components = getMatchedComponents(to)
|
||||
|
||||
// If no Components matched, generate 404
|
||||
if (!Components.length) {
|
||||
// Default layout
|
||||
await callMiddleware.call(this, Components, context)
|
||||
if (context._redirected) return
|
||||
|
||||
// Load layout for error page
|
||||
layout = await this.loadLayout(typeof NuxtError.layout === 'function' ? NuxtError.layout(context) : NuxtError.layout)
|
||||
await callMiddleware.call(this, Components, context, layout)
|
||||
if (context._redirected) return
|
||||
|
||||
this.error({ statusCode: 404, message: 'This page could not be found.' })
|
||||
return next()
|
||||
}
|
||||
|
||||
// Update ._data and other properties if hot reloaded
|
||||
Components.forEach(function (Component) {
|
||||
Components.forEach(Component => {
|
||||
if (Component._Ctor && Component._Ctor.options) {
|
||||
Component.options.asyncData = Component._Ctor.options.asyncData
|
||||
Component.options.fetch = Component._Ctor.options.fetch
|
||||
}
|
||||
})
|
||||
|
||||
// Apply transitions
|
||||
this.setTransitions(mapTransitions(Components, to, from))
|
||||
|
||||
try {
|
||||
// Set layout
|
||||
// Call middleware
|
||||
await callMiddleware.call(this, Components, context)
|
||||
if (context._redirected) return
|
||||
layout = Components[0].options.layout
|
||||
|
||||
// Set layout
|
||||
let layout = Components[0].options.layout
|
||||
if (typeof layout === 'function') {
|
||||
layout = layout(context)
|
||||
}
|
||||
layout = await this.loadLayout(layout)
|
||||
|
||||
// Call middleware for layout
|
||||
await callMiddleware.call(this, Components, context, layout)
|
||||
if (context._redirected) return
|
||||
// Pass validation?
|
||||
|
||||
// Call .validate()
|
||||
let isValid = true
|
||||
Components.forEach((Component) => {
|
||||
Components.forEach(Component => {
|
||||
if (!isValid) return
|
||||
if (typeof Component.options.validate !== 'function') return
|
||||
isValid = Component.options.validate({
|
||||
params: to.params || {},
|
||||
query : to.query || {}<%= (store ? ', store: context.store' : '') %>
|
||||
query : to.query || {},
|
||||
<% if(store) { %>store: context.store <% } %>
|
||||
})
|
||||
})
|
||||
// ...If .validate() returned false
|
||||
if (!isValid) {
|
||||
this.error({ statusCode: 404, message: 'This page could not be found.' })
|
||||
return next()
|
||||
}
|
||||
|
||||
// Call asyncData & fetch hooks on components matched by the route.
|
||||
await Promise.all(Components.map((Component, i) => {
|
||||
// Check if only children route changed
|
||||
Component._path = compile(to.matched[i].path)(to.params)
|
||||
if (!this._hadError && Component._path === _lastPaths[i] && (i + 1) !== Components.length) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
let promises = []
|
||||
// asyncData method
|
||||
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
|
||||
var promise = promisify(Component.options.asyncData, context)
|
||||
promise.then((asyncDataResult) => {
|
||||
|
||||
const hasAsyncData = Component.options.asyncData && typeof Component.options.asyncData === 'function'
|
||||
const hasFetch = !!Component.options.fetch
|
||||
<% if(loading) { %>const loadingIncrease = (hasAsyncData && hasFetch) ? 30 : 45<% } %>
|
||||
|
||||
// Call asyncData(context)
|
||||
if (hasAsyncData) {
|
||||
const promise = promisify(Component.options.asyncData, context)
|
||||
.then(asyncDataResult => {
|
||||
applyAsyncData(Component, asyncDataResult)
|
||||
<%= (loading ? 'this.$loading.increase && this.$loading.increase(30)' : '') %>
|
||||
<% if(loading) { %>if(this.$loading.increase) this.$loading.increase(loadingIncrease)<% } %>
|
||||
})
|
||||
promises.push(promise)
|
||||
}
|
||||
if (Component.options.fetch) {
|
||||
var p = Component.options.fetch(context)
|
||||
if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) { p = Promise.resolve(p) }
|
||||
<%= (loading ? 'p.then(() => this.$loading.increase && this.$loading.increase(30))' : '') %>
|
||||
|
||||
// Call fetch(context)
|
||||
if (hasFetch) {
|
||||
let p = Component.options.fetch(context)
|
||||
if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) {
|
||||
p = Promise.resolve(p)
|
||||
}
|
||||
p.then(fetchResult => {
|
||||
<% if(loading) { %>if(this.$loading.increase) this.$loading.increase(loadingIncrease)<% } %>
|
||||
})
|
||||
promises.push(p)
|
||||
}
|
||||
|
||||
return Promise.all(promises)
|
||||
}))
|
||||
|
||||
_lastPaths = Components.map((Component, i) => compile(to.matched[i].path)(to.params))
|
||||
<%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
|
||||
|
||||
<% if(loading) { %>if(this.$loading.finish) this.$loading.finish()<% } %>
|
||||
|
||||
// If not redirected
|
||||
if (!nextCalled) {
|
||||
next()
|
||||
}
|
||||
if (!nextCalled) next()
|
||||
|
||||
} catch (error) {
|
||||
if (!error) error = {}
|
||||
_lastPaths = []
|
||||
error.statusCode = error.statusCode || error.status || (error.response && error.response.status) || 500
|
||||
|
||||
// Load error layout
|
||||
let layout = NuxtError.layout
|
||||
if (typeof layout === 'function') {
|
||||
layout = layout(context)
|
||||
}
|
||||
this.loadLayout(layout)
|
||||
.then(() => {
|
||||
this.error(error)
|
||||
next(false)
|
||||
})
|
||||
await this.loadLayout(layout)
|
||||
|
||||
this.error(error)
|
||||
next(false)
|
||||
}
|
||||
}
|
||||
|
||||
@ -212,46 +327,74 @@ function normalizeComponents (to, ___) {
|
||||
}
|
||||
|
||||
// When navigating on a different route but the same component is used, Vue.js
|
||||
// will not update the instance data, so we have to update $data ourselves
|
||||
// Will not update the instance data, so we have to update $data ourselves
|
||||
function fixPrepatch (to, ___) {
|
||||
if (this._hashChanged) return
|
||||
|
||||
Vue.nextTick(() => {
|
||||
let instances = getMatchedComponentsInstances(to)
|
||||
const instances = getMatchedComponentsInstances(to)
|
||||
|
||||
_lastComponentsFiles = instances.map((instance, i) => {
|
||||
if (!instance) return '';
|
||||
|
||||
if (_lastPaths[i] === instance.constructor._path && typeof instance.constructor.options.data === 'function') {
|
||||
let newData = instance.constructor.options.data.call(instance)
|
||||
const newData = instance.constructor.options.data.call(instance)
|
||||
for (let key in newData) {
|
||||
Vue.set(instance.$data, key, newData[key])
|
||||
}
|
||||
}
|
||||
|
||||
return instance.constructor.options.__file
|
||||
})
|
||||
// hide error component if no error
|
||||
|
||||
// Hide error component if no error
|
||||
if (this._hadError && this._dateLastError === this.$options._nuxt.dateErr) {
|
||||
this.error()
|
||||
}
|
||||
|
||||
// Set layout
|
||||
let layout = this.$options._nuxt.err ? NuxtError.layout : to.matched[0].components.default.options.layout
|
||||
if (typeof layout === 'function') {
|
||||
layout = layout(this._context)
|
||||
}
|
||||
this.setLayout(layout)
|
||||
// hot reloading
|
||||
|
||||
<% if (isDev) { %>
|
||||
// Hot reloading
|
||||
setTimeout(() => hotReloadAPI(this), 100)
|
||||
<% } %>
|
||||
})
|
||||
}
|
||||
|
||||
function nuxtReady (app) {
|
||||
window._nuxtReadyCbs.forEach((cb) => {
|
||||
if (typeof cb === 'function') {
|
||||
cb(app)
|
||||
}
|
||||
})
|
||||
// Special JSDOM
|
||||
if (typeof window._onNuxtLoaded === 'function') {
|
||||
window._onNuxtLoaded(app)
|
||||
}
|
||||
// Add router hooks
|
||||
router.afterEach(function (to, from) {
|
||||
app.$nuxt.$emit('routeChanged', to, from)
|
||||
})
|
||||
}
|
||||
|
||||
<% if (isDev) { %>
|
||||
// Special hot reload with asyncData(context)
|
||||
function hotReloadAPI (_app) {
|
||||
if (!module.hot) return
|
||||
|
||||
let $components = []
|
||||
let $nuxt = _app.$nuxt
|
||||
|
||||
while ($nuxt && $nuxt.$children && $nuxt.$children.length) {
|
||||
$nuxt.$children.forEach(function (child, i) {
|
||||
$nuxt.$children.forEach((child, i) => {
|
||||
if (child.$vnode.data.nuxtChild) {
|
||||
let hasAlready = false
|
||||
$components.forEach(function (component) {
|
||||
$components.forEach(component => {
|
||||
if (component.$options.__file === child.$options.__file) {
|
||||
hasAlready = true
|
||||
}
|
||||
@ -263,13 +406,16 @@ function hotReloadAPI (_app) {
|
||||
$nuxt = child
|
||||
})
|
||||
}
|
||||
|
||||
$components.forEach(addHotReload.bind(_app))
|
||||
}
|
||||
|
||||
function addHotReload ($component, depth) {
|
||||
if ($component.$vnode.data._hasHotReload) return
|
||||
$component.$vnode.data._hasHotReload = true
|
||||
|
||||
var _forceUpdate = $component.$forceUpdate.bind($component.$parent)
|
||||
|
||||
$component.$vnode.context.$forceUpdate = () => {
|
||||
let Components = getMatchedComponents(router.currentRoute)
|
||||
let Component = Components[depth]
|
||||
@ -329,106 +475,80 @@ function addHotReload ($component, depth) {
|
||||
})
|
||||
}
|
||||
}
|
||||
<% } %>
|
||||
|
||||
// Load vue app
|
||||
const NUXT = window.__NUXT__ || {}
|
||||
NUXT.components = window.__COMPONENTS__ || null
|
||||
// Get matched components
|
||||
const resolveComponents = function (router) {
|
||||
const path = getLocation(router.options.base)
|
||||
return flatMapComponents(router.match(path), (Component, _, match, key, index) => {
|
||||
if (typeof Component === 'function' && !Component.options) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const _resolve = (Component) => {
|
||||
Component = sanitizeComponent(Component)
|
||||
if (NUXT.serverRendered) {
|
||||
applyAsyncData(Component, NUXT.data[index])
|
||||
if (NUXT.components) {
|
||||
Component.options.components = Object.assign(Component.options.components, NUXT.components[index])
|
||||
}
|
||||
Component._Ctor = Component
|
||||
}
|
||||
match.components[key] = Component
|
||||
resolve(Component)
|
||||
}
|
||||
Component().then(_resolve).catch(reject)
|
||||
})
|
||||
}
|
||||
Component = sanitizeComponent(Component)
|
||||
match.components[key] = Component
|
||||
return Component
|
||||
})
|
||||
}
|
||||
|
||||
function nuxtReady (app) {
|
||||
window._nuxtReadyCbs.forEach((cb) => {
|
||||
if (typeof cb === 'function') {
|
||||
cb(app)
|
||||
}
|
||||
})
|
||||
// Special JSDOM
|
||||
if (typeof window._onNuxtLoaded === 'function') {
|
||||
window._onNuxtLoaded(app)
|
||||
}
|
||||
// Add router hooks
|
||||
router.afterEach(function (to, from) {
|
||||
app.$nuxt.$emit('routeChanged', to, from)
|
||||
})
|
||||
}
|
||||
|
||||
createApp()
|
||||
.then(async (__app) => {
|
||||
async function mountApp(__app) {
|
||||
// Set global variables
|
||||
app = __app.app
|
||||
router = __app.router
|
||||
<%= (store ? 'store = __app.store' : '') %>
|
||||
<% if (store) { %>store = __app.store <% } %>
|
||||
|
||||
// Resolve route components
|
||||
const Components = await Promise.all(resolveComponents(router))
|
||||
|
||||
// Create Vue instance
|
||||
const _app = new Vue(app)
|
||||
|
||||
// Load layout
|
||||
const layout = NUXT.layout || 'default'
|
||||
await _app.loadLayout(layout)
|
||||
_app.setLayout(layout)
|
||||
|
||||
// Mounts Vue app to DOM element
|
||||
const mountApp = () => {
|
||||
_app.$mount('#__nuxt')
|
||||
|
||||
// Listen for first Vue update
|
||||
Vue.nextTick(() => {
|
||||
// Hot reloading
|
||||
hotReloadAPI(_app)
|
||||
// Call window.onNuxtReady callbacks
|
||||
nuxtReady(_app)
|
||||
<% if (isDev) { %>
|
||||
// Enable hot reloading
|
||||
hotReloadAPI(_app)
|
||||
<% } %>
|
||||
})
|
||||
}
|
||||
|
||||
// Enable transitions
|
||||
_app.setTransitions = _app.$options._nuxt.setTransitions.bind(_app)
|
||||
if (Components.length) {
|
||||
_app.setTransitions(mapTransitions(Components, router.currentRoute))
|
||||
_lastPaths = router.currentRoute.matched.map((route) => compile(route.path)(router.currentRoute.params))
|
||||
_lastComponentsFiles = Components.map((Component) => Component.options.__file)
|
||||
_lastPaths = router.currentRoute.matched.map(route => compile(route.path)(router.currentRoute.params))
|
||||
_lastComponentsFiles = Components.map(Component => Component.options.__file)
|
||||
}
|
||||
|
||||
// Initialize error handler
|
||||
_app.error = _app.$options._nuxt.error.bind(_app)
|
||||
_app.$loading = {} // to avoid error while _app.$nuxt does not exist
|
||||
_app.$loading = {} // To avoid error while _app.$nuxt does not exist
|
||||
if (NUXT.error) _app.error(NUXT.error)
|
||||
|
||||
// Add router hooks
|
||||
router.beforeEach(loadAsyncComponents.bind(_app))
|
||||
router.beforeEach(render.bind(_app))
|
||||
router.afterEach(normalizeComponents)
|
||||
router.afterEach(fixPrepatch.bind(_app))
|
||||
|
||||
// If page already is server rendered
|
||||
if (NUXT.serverRendered) {
|
||||
mountApp()
|
||||
return
|
||||
}
|
||||
render.call(_app, router.currentRoute, router.currentRoute, function (path) {
|
||||
if (path) {
|
||||
let mounted = false
|
||||
router.afterEach(function () {
|
||||
if (mounted) return
|
||||
mounted = true
|
||||
mountApp()
|
||||
})
|
||||
router.push(path)
|
||||
|
||||
render.call(_app, router.currentRoute, router.currentRoute, path => {
|
||||
if (!path) {
|
||||
normalizeComponents(router.currentRoute, router.currentRoute)
|
||||
fixPrepatch.call(_app, router.currentRoute, router.currentRoute)
|
||||
mountApp()
|
||||
return
|
||||
}
|
||||
normalizeComponents(router.currentRoute, router.currentRoute)
|
||||
fixPrepatch.call(_app, router.currentRoute, router.currentRoute)
|
||||
mountApp()
|
||||
|
||||
// Push the path and then mount app
|
||||
let mounted = false
|
||||
router.afterEach(() => {
|
||||
if (mounted) return
|
||||
mounted = true
|
||||
mountApp()
|
||||
})
|
||||
router.push(path)
|
||||
})
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[nuxt.js] Cannot load components', err) // eslint-disable-line no-console
|
||||
})
|
||||
}
|
@ -1,17 +1,14 @@
|
||||
'use strict'
|
||||
|
||||
import 'es6-promise/auto'
|
||||
import Vue from 'vue'
|
||||
import Meta from 'vue-meta'
|
||||
import { createRouter } from './router.js'
|
||||
<% if (store) { %>import { createStore } from './store.js'<% } %>
|
||||
import NuxtChild from './components/nuxt-child.js'
|
||||
import NuxtLink from './components/nuxt-link.js'
|
||||
import NuxtError from '<%= components.ErrorPage ? components.ErrorPage : "./components/nuxt-error.vue" %>'
|
||||
import Nuxt from './components/nuxt.vue'
|
||||
import App from '<%= appPath %>'
|
||||
|
||||
import { getContext } from './utils'
|
||||
<% if (store) { %>import { createStore } from './store.js'<% } %>
|
||||
|
||||
if (process.browser) {
|
||||
// window.onNuxtReady(() => console.log('Ready')) hook
|
||||
@ -22,11 +19,24 @@ if (process.browser) {
|
||||
}
|
||||
}
|
||||
|
||||
// Import SSR plugins
|
||||
<% plugins.forEach(function (plugin) { if (plugin.ssr)
|
||||
{ %>let <%= plugin.name %> = require('<%= relativeToBuild(plugin.src) %>')
|
||||
<% if (plugins.filter(p => p.ssr).length) { %>
|
||||
// Require plugins
|
||||
<% plugins.filter(p => p.ssr).forEach(plugin => { %>
|
||||
let <%= plugin.name %> = require('<%= relativeToBuild(plugin.src) %>')
|
||||
<%= plugin.name %> = <%= plugin.name %>.default || <%= plugin.name %>
|
||||
<% }}) %>
|
||||
<% }) %>
|
||||
<% } %>
|
||||
|
||||
<% if (plugins.filter(p => !p.ssr).length) { %>
|
||||
// Require browser-only plugins
|
||||
if (process.browser) {
|
||||
<% plugins.filter(p => !p.ssr).forEach(plugin => { %>
|
||||
let <%= plugin.name %> = require('<%= relativeToBuild(plugin.src) %>')
|
||||
<%= plugin.name %> = <%= plugin.name %>.default || <%= plugin.name %>
|
||||
<% }) %>
|
||||
}
|
||||
<% } %>
|
||||
|
||||
|
||||
// Component: <nuxt-child>
|
||||
Vue.component(NuxtChild.name, NuxtChild)
|
||||
@ -48,35 +58,34 @@ const defaultTransition = <%=
|
||||
.replace('beforeEnter(', 'function(').replace('enter(', 'function(').replace('afterEnter(', 'function(')
|
||||
.replace('enterCancelled(', 'function(').replace('beforeLeave(', 'function(').replace('leave(', 'function(')
|
||||
.replace('afterLeave(', 'function(').replace('leaveCancelled(', 'function(')
|
||||
%>
|
||||
%>
|
||||
|
||||
async function createApp (ssrContext) {
|
||||
<% if (store) { %>
|
||||
const store = createStore()
|
||||
<% } %>
|
||||
const router = createRouter()
|
||||
|
||||
<% if (store) { %>const store = createStore()<% } %>
|
||||
|
||||
if (process.server && ssrContext && ssrContext.url) {
|
||||
await new Promise((resolve, reject) => {
|
||||
router.push(ssrContext.url, resolve, reject)
|
||||
})
|
||||
}
|
||||
|
||||
<% if (store) { %>
|
||||
if (process.browser) {
|
||||
<% if (store) { %>
|
||||
// Replace store state before calling plugins
|
||||
if (window.__NUXT__ && window.__NUXT__.state) {
|
||||
store.replaceState(window.__NUXT__.state)
|
||||
}
|
||||
<% } %>
|
||||
}
|
||||
<% } %>
|
||||
|
||||
// root instance
|
||||
// Create Root instance
|
||||
// here we inject the router and store to all child components,
|
||||
// making them available everywhere as `this.$router` and `this.$store`.
|
||||
let app = {
|
||||
const app = {
|
||||
router,
|
||||
<%= (store ? 'store,' : '') %>
|
||||
<% if(store) { %> store,<% } %>
|
||||
_nuxt: {
|
||||
defaultTransition,
|
||||
transitions: [ defaultTransition ],
|
||||
@ -107,42 +116,46 @@ async function createApp (ssrContext) {
|
||||
const _nuxt = this._nuxt || this.$options._nuxt
|
||||
_nuxt.dateErr = Date.now()
|
||||
_nuxt.err = err
|
||||
console.error(err)
|
||||
console.error('[nuxt] ' + err)
|
||||
return err
|
||||
}
|
||||
},
|
||||
...App
|
||||
}
|
||||
|
||||
const next = ssrContext ? ssrContext.next : (location) => app.router.push(location)
|
||||
const next = ssrContext ? ssrContext.next : location => app.router.push(location)
|
||||
|
||||
const ctx = getContext({
|
||||
isServer: !!ssrContext,
|
||||
isClient: !ssrContext,
|
||||
route: router.currentRoute,
|
||||
next,
|
||||
error: app._nuxt.error.bind(app),
|
||||
<%= (store ? 'store,' : '') %>
|
||||
<% if(store) { %> store,<% } %>
|
||||
req: ssrContext ? ssrContext.req : undefined,
|
||||
res: ssrContext ? ssrContext.res : undefined,
|
||||
}, app)
|
||||
|
||||
// Inject external plugins
|
||||
<% plugins.forEach(function (plugin) {
|
||||
if (plugin.ssr) { %>
|
||||
if (typeof <%= plugin.name %> === 'function') {
|
||||
await <%= plugin.name %>(ctx)
|
||||
}
|
||||
<% } else { %>
|
||||
if (process.browser) {
|
||||
let <%= plugin.name %> = require('<%= relativeToBuild(plugin.src) %>')
|
||||
<%= plugin.name %> = <%= plugin.name %>.default || <%= plugin.name %>
|
||||
if (typeof <%= plugin.name %> === 'function') {
|
||||
await <%= plugin.name %>(ctx)
|
||||
}
|
||||
}
|
||||
<% }
|
||||
}) %>
|
||||
<% if (plugins.filter(p => p.ssr).length) { %>
|
||||
<% plugins.filter(p => p.ssr).forEach(plugin => { %>
|
||||
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(ctx)
|
||||
<% }) %>
|
||||
<% } %>
|
||||
|
||||
return { app, router<%= (store ? ', store' : '') %> }
|
||||
<% if (plugins.filter(p => !p.ssr).length) { %>
|
||||
if (process.browser) {
|
||||
<% plugins.filter(p => !p.ssr).forEach(plugin => { %>
|
||||
if (typeof <%= plugin.name %> === 'function') await <%= plugin.name %>(ctx)
|
||||
<% }) %>
|
||||
}
|
||||
<% } %>
|
||||
|
||||
return {
|
||||
app,
|
||||
router,
|
||||
<% if(store) { %> store <% } %>
|
||||
}
|
||||
}
|
||||
|
||||
export { createApp, NuxtError }
|
||||
|
@ -1,5 +1,3 @@
|
||||
'use strict'
|
||||
|
||||
import Vue from 'vue'
|
||||
import Router from 'vue-router'
|
||||
|
||||
@ -7,7 +5,7 @@ Vue.use(Router)
|
||||
|
||||
<%
|
||||
function recursiveRoutes(routes, tab, components) {
|
||||
var res = ''
|
||||
let res = ''
|
||||
routes.forEach((route, i) => {
|
||||
route._name = '_' + hash(route.component)
|
||||
components.push({ _name: route._name, component: route.component, name: route.name })
|
||||
@ -20,31 +18,30 @@ function recursiveRoutes(routes, tab, components) {
|
||||
})
|
||||
return res
|
||||
}
|
||||
var _components = []
|
||||
var _routes = recursiveRoutes(router.routes, '\t\t', _components)
|
||||
uniqBy(_components, '_name').forEach((route) => { %>
|
||||
const <%= route._name %> = () => import('<%= relativeToBuild(route.component) %>' /* webpackChunkName: "pages/<%= route.name %>" */).then(m => m.default || m)
|
||||
const _components = []
|
||||
const _routes = recursiveRoutes(router.routes, '\t\t', _components)
|
||||
uniqBy(_components, '_name').forEach((route) => { %>const <%= route._name %> = () => import('<%= relativeToBuild(route.component) %>' /* webpackChunkName: "pages/<%= route.name %>" */).then(m => m.default || m)
|
||||
<% }) %>
|
||||
|
||||
<% if (router.scrollBehavior) { %>
|
||||
const scrollBehavior = <%= serialize(router.scrollBehavior).replace('scrollBehavior(', 'function(') %>
|
||||
<% } else { %>
|
||||
const scrollBehavior = (to, from, savedPosition) => {
|
||||
// savedPosition is only available for popstate navigations.
|
||||
// SavedPosition is only available for popstate navigations.
|
||||
if (savedPosition) {
|
||||
return savedPosition
|
||||
} else {
|
||||
let position = {}
|
||||
// if no children detected
|
||||
// If no children detected
|
||||
if (to.matched.length < 2) {
|
||||
// scroll to the top of the page
|
||||
// Scroll to the top of the page
|
||||
position = { x: 0, y: 0 }
|
||||
}
|
||||
else if (to.matched.some((r) => r.components.default.options.scrollToTop)) {
|
||||
// if one of the children has scrollToTop option set to true
|
||||
// If one of the children has scrollToTop option set to true
|
||||
position = { x: 0, y: 0 }
|
||||
}
|
||||
// if link has anchor, scroll to anchor by returning the selector
|
||||
// If link has anchor, scroll to anchor by returning the selector
|
||||
if (to.hash) {
|
||||
position = { selector: to.hash }
|
||||
}
|
||||
@ -61,7 +58,7 @@ export function createRouter () {
|
||||
linkExactActiveClass: '<%= router.linkExactActiveClass %>',
|
||||
scrollBehavior,
|
||||
routes: [
|
||||
<%= _routes %>
|
||||
<%= _routes %>
|
||||
],
|
||||
fallback: <%= router.fallback %>
|
||||
})
|
||||
|
@ -77,13 +77,12 @@ export default async context => {
|
||||
// Resolve components
|
||||
let Components = []
|
||||
try {
|
||||
Components = await Promise.all(getMatchedComponents(router.match(context.url)).map((Component) => new Promise((resolve, reject) => {
|
||||
Components = await Promise.all(getMatchedComponents(router.match(context.url)).map(Component => {
|
||||
if (typeof Component !== 'function' || Component.super === Vue) {
|
||||
return resolve(sanitizeComponent(Component))
|
||||
return sanitizeComponent(Component)
|
||||
}
|
||||
const _resolve = (Component) => resolve(sanitizeComponent(Component))
|
||||
Component().then(_resolve).catch(reject)
|
||||
})))
|
||||
return Component().then(Component => sanitizeComponent(Component))
|
||||
}))
|
||||
} catch (err) {
|
||||
// Throw back error to renderRoute()
|
||||
throw err
|
||||
|
@ -1,4 +1,3 @@
|
||||
'use strict'
|
||||
import Vue from 'vue'
|
||||
|
||||
const noopData = () => ({})
|
||||
|
Loading…
Reference in New Issue
Block a user