client.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import Vue from 'vue'
  2. import middleware from './middleware'
  3. import { createApp, NuxtError } from './index'
  4. import {
  5. applyAsyncData,
  6. sanitizeComponent,
  7. resolveRouteComponents,
  8. getMatchedComponents,
  9. getMatchedComponentsInstances,
  10. flatMapComponents,
  11. setContext,
  12. middlewareSeries,
  13. promisify,
  14. getLocation,
  15. compile,
  16. getQueryDiff
  17. } from './utils'
  18. const noopData = () => { return {} }
  19. const noopFetch = () => {}
  20. // Global shared references
  21. let _lastPaths = []
  22. let app
  23. let router
  24. let store
  25. // Try to rehydrate SSR data from window
  26. const NUXT = window.__NUXT__ || {}
  27. // Create and mount App
  28. createApp()
  29. .then(mountApp)
  30. .catch(err => {
  31. if (err.message === 'ERR_REDIRECT') {
  32. return // Wait for browser to redirect...
  33. }
  34. console.error('[nuxt] Error while initializing app', err)
  35. })
  36. function componentOption(component, key, ...args) {
  37. if (!component || !component.options || !component.options[key]) {
  38. return {}
  39. }
  40. const option = component.options[key]
  41. if (typeof option === 'function') {
  42. return option(...args)
  43. }
  44. return option
  45. }
  46. function mapTransitions(Components, to, from) {
  47. const componentTransitions = component => {
  48. const transition = componentOption(component, 'transition', to, from) || {}
  49. return (typeof transition === 'string' ? { name: transition } : transition)
  50. }
  51. return Components.map(Component => {
  52. // Clone original object to prevent overrides
  53. const transitions = Object.assign({}, componentTransitions(Component))
  54. // Combine transitions & prefer `leave` transitions of 'from' route
  55. if (from && from.matched.length && from.matched[0].components.default) {
  56. const from_transitions = componentTransitions(from.matched[0].components.default)
  57. Object.keys(from_transitions)
  58. .filter(key => from_transitions[key] && key.toLowerCase().indexOf('leave') !== -1)
  59. .forEach(key => { transitions[key] = from_transitions[key] })
  60. }
  61. return transitions
  62. })
  63. }
  64. async function loadAsyncComponents (to, from, next) {
  65. // Check if route path changed (this._pathChanged), only if the page is not an error (for validate())
  66. this._pathChanged = !!app.nuxt.err || from.path !== to.path
  67. this._queryChanged = JSON.stringify(to.query) !== JSON.stringify(from.query)
  68. this._diffQuery = (this._queryChanged ? getQueryDiff(to.query, from.query) : [])
  69. if (this._pathChanged && this.$loading.start) {
  70. this.$loading.start()
  71. }
  72. try {
  73. const Components = await resolveRouteComponents(to)
  74. if (!this._pathChanged && this._queryChanged) {
  75. // Add a marker on each component that it needs to refresh or not
  76. const startLoader = Components.some((Component) => {
  77. const watchQuery = Component.options.watchQuery
  78. if (watchQuery === true) return true
  79. if (Array.isArray(watchQuery)) {
  80. return watchQuery.some((key) => this._diffQuery[key])
  81. }
  82. return false
  83. })
  84. if (startLoader && this.$loading.start) {
  85. this.$loading.start()
  86. }
  87. }
  88. // Call next()
  89. next()
  90. } catch (err) {
  91. err = err || {}
  92. const statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500
  93. this.error({ statusCode, message: err.message })
  94. this.$nuxt.$emit('routeChanged', to, from, err)
  95. next(false)
  96. }
  97. }
  98. function applySSRData(Component, ssrData) {
  99. if (NUXT.serverRendered && ssrData) {
  100. applyAsyncData(Component, ssrData)
  101. }
  102. Component._Ctor = Component
  103. return Component
  104. }
  105. // Get matched components
  106. function resolveComponents(router) {
  107. const path = getLocation(router.options.base, router.options.mode)
  108. return flatMapComponents(router.match(path), async (Component, _, match, key, index) => {
  109. // If component is not resolved yet, resolve it
  110. if (typeof Component === 'function' && !Component.options) {
  111. Component = await Component()
  112. }
  113. // Sanitize it and save it
  114. const _Component = applySSRData(sanitizeComponent(Component), NUXT.data ? NUXT.data[index] : null)
  115. match.components[key] = _Component
  116. return _Component
  117. })
  118. }
  119. function callMiddleware (Components, context, layout) {
  120. let midd = ["check-auth"]
  121. let unknownMiddleware = false
  122. // If layout is undefined, only call global middleware
  123. if (typeof layout !== 'undefined') {
  124. midd = [] // Exclude global middleware if layout defined (already called before)
  125. if (layout.middleware) {
  126. midd = midd.concat(layout.middleware)
  127. }
  128. Components.forEach(Component => {
  129. if (Component.options.middleware) {
  130. midd = midd.concat(Component.options.middleware)
  131. }
  132. })
  133. }
  134. midd = midd.map(name => {
  135. if (typeof name === 'function') return name
  136. if (typeof middleware[name] !== 'function') {
  137. unknownMiddleware = true
  138. this.error({ statusCode: 500, message: 'Unknown middleware ' + name })
  139. }
  140. return middleware[name]
  141. })
  142. if (unknownMiddleware) return
  143. return middlewareSeries(midd, context)
  144. }
  145. async function render (to, from, next) {
  146. if (this._pathChanged === false && this._queryChanged === false) return next()
  147. // nextCalled is true when redirected
  148. let nextCalled = false
  149. const _next = path => {
  150. if (from.path === path.path && this.$loading.finish) this.$loading.finish()
  151. if (from.path !== path.path && this.$loading.pause) this.$loading.pause()
  152. if (nextCalled) return
  153. nextCalled = true
  154. const matches = []
  155. _lastPaths = getMatchedComponents(from, matches).map((Component, i) => compile(from.matched[matches[i]].path)(from.params))
  156. next(path)
  157. }
  158. // Update context
  159. await setContext(app, {
  160. route: to,
  161. from,
  162. next: _next.bind(this)
  163. })
  164. this._dateLastError = app.nuxt.dateErr
  165. this._hadError = !!app.nuxt.err
  166. // Get route's matched components
  167. const matches = []
  168. const Components = getMatchedComponents(to, matches)
  169. // If no Components matched, generate 404
  170. if (!Components.length) {
  171. // Default layout
  172. await callMiddleware.call(this, Components, app.context)
  173. if (nextCalled) return
  174. // Load layout for error page
  175. const layout = await this.loadLayout(typeof NuxtError.layout === 'function' ? NuxtError.layout(app.context) : NuxtError.layout)
  176. await callMiddleware.call(this, Components, app.context, layout)
  177. if (nextCalled) return
  178. // Show error page
  179. app.context.error({ statusCode: 404, message: 'This page could not be found' })
  180. return next()
  181. }
  182. // Update ._data and other properties if hot reloaded
  183. Components.forEach(Component => {
  184. if (Component._Ctor && Component._Ctor.options) {
  185. Component.options.asyncData = Component._Ctor.options.asyncData
  186. Component.options.fetch = Component._Ctor.options.fetch
  187. }
  188. })
  189. // Apply transitions
  190. this.setTransitions(mapTransitions(Components, to, from))
  191. try {
  192. // Call middleware
  193. await callMiddleware.call(this, Components, app.context)
  194. if (nextCalled) return
  195. if (app.context._errored) return next()
  196. // Set layout
  197. let layout = Components[0].options.layout
  198. if (typeof layout === 'function') {
  199. layout = layout(app.context)
  200. }
  201. layout = await this.loadLayout(layout)
  202. // Call middleware for layout
  203. await callMiddleware.call(this, Components, app.context, layout)
  204. if (nextCalled) return
  205. if (app.context._errored) return next()
  206. // Call .validate()
  207. let isValid = true
  208. Components.forEach(Component => {
  209. if (!isValid) return
  210. if (typeof Component.options.validate !== 'function') return
  211. isValid = Component.options.validate({
  212. params: to.params || {},
  213. query : to.query || {},
  214. store
  215. })
  216. })
  217. // ...If .validate() returned false
  218. if (!isValid) {
  219. this.error({ statusCode: 404, message: 'This page could not be found' })
  220. return next()
  221. }
  222. // Call asyncData & fetch hooks on components matched by the route.
  223. await Promise.all(Components.map((Component, i) => {
  224. // Check if only children route changed
  225. Component._path = compile(to.matched[matches[i]].path)(to.params)
  226. Component._dataRefresh = false
  227. // Check if Component need to be refreshed (call asyncData & fetch)
  228. // Only if its slug has changed or is watch query changes
  229. if (this._pathChanged && Component._path !== _lastPaths[i]) {
  230. Component._dataRefresh = true
  231. } else if (!this._pathChanged && this._queryChanged) {
  232. const watchQuery = Component.options.watchQuery
  233. if (watchQuery === true) {
  234. Component._dataRefresh = true
  235. } else if (Array.isArray(watchQuery)) {
  236. Component._dataRefresh = watchQuery.some((key) => this._diffQuery[key])
  237. }
  238. }
  239. if (!this._hadError && this._isMounted && !Component._dataRefresh) {
  240. return Promise.resolve()
  241. }
  242. let promises = []
  243. const hasAsyncData = Component.options.asyncData && typeof Component.options.asyncData === 'function'
  244. const hasFetch = !!Component.options.fetch
  245. const loadingIncrease = (hasAsyncData && hasFetch) ? 30 : 45
  246. // Call asyncData(context)
  247. if (hasAsyncData) {
  248. const promise = promisify(Component.options.asyncData, app.context)
  249. .then(asyncDataResult => {
  250. applyAsyncData(Component, asyncDataResult)
  251. if(this.$loading.increase) this.$loading.increase(loadingIncrease)
  252. })
  253. promises.push(promise)
  254. }
  255. // Call fetch(context)
  256. if (hasFetch) {
  257. let p = Component.options.fetch(app.context)
  258. if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) {
  259. p = Promise.resolve(p)
  260. }
  261. p.then(fetchResult => {
  262. if(this.$loading.increase) this.$loading.increase(loadingIncrease)
  263. })
  264. promises.push(p)
  265. }
  266. return Promise.all(promises)
  267. }))
  268. // If not redirected
  269. if (!nextCalled) {
  270. if(this.$loading.finish) this.$loading.finish()
  271. _lastPaths = Components.map((Component, i) => compile(to.matched[matches[i]].path)(to.params))
  272. next()
  273. }
  274. } catch (error) {
  275. if (!error) error = {}
  276. _lastPaths = []
  277. error.statusCode = error.statusCode || error.status || (error.response && error.response.status) || 500
  278. // Load error layout
  279. let layout = NuxtError.layout
  280. if (typeof layout === 'function') {
  281. layout = layout(app.context)
  282. }
  283. await this.loadLayout(layout)
  284. this.error(error)
  285. this.$nuxt.$emit('routeChanged', to, from, error)
  286. next(false)
  287. }
  288. }
  289. // Fix components format in matched, it's due to code-splitting of vue-router
  290. function normalizeComponents (to, ___) {
  291. flatMapComponents(to, (Component, _, match, key) => {
  292. if (typeof Component === 'object' && !Component.options) {
  293. // Updated via vue-router resolveAsyncComponents()
  294. Component = Vue.extend(Component)
  295. Component._Ctor = Component
  296. match.components[key] = Component
  297. }
  298. return Component
  299. })
  300. }
  301. function showNextPage(to) {
  302. // Hide error component if no error
  303. if (this._hadError && this._dateLastError === this.$options.nuxt.dateErr) {
  304. this.error()
  305. }
  306. // Set layout
  307. let layout = this.$options.nuxt.err ? NuxtError.layout : to.matched[0].components.default.options.layout
  308. if (typeof layout === 'function') {
  309. layout = layout(app.context)
  310. }
  311. this.setLayout(layout)
  312. }
  313. // When navigating on a different route but the same component is used, Vue.js
  314. // Will not update the instance data, so we have to update $data ourselves
  315. function fixPrepatch(to, ___) {
  316. if (this._pathChanged === false && this._queryChanged === false) return
  317. Vue.nextTick(() => {
  318. const matches = []
  319. const instances = getMatchedComponentsInstances(to, matches)
  320. instances.forEach((instance, i) => {
  321. if (!instance) return
  322. // if (!this._queryChanged && to.matched[matches[i]].path.indexOf(':') === -1 && to.matched[matches[i]].path.indexOf('*') === -1) return // If not a dynamic route, skip
  323. if (instance.constructor._dataRefresh && _lastPaths[i] === instance.constructor._path && typeof instance.constructor.options.data === 'function') {
  324. const newData = instance.constructor.options.data.call(instance)
  325. for (let key in newData) {
  326. Vue.set(instance.$data, key, newData[key])
  327. }
  328. }
  329. })
  330. showNextPage.call(this, to)
  331. })
  332. }
  333. function nuxtReady (_app) {
  334. window._nuxtReadyCbs.forEach((cb) => {
  335. if (typeof cb === 'function') {
  336. cb(_app)
  337. }
  338. })
  339. // Special JSDOM
  340. if (typeof window._onNuxtLoaded === 'function') {
  341. window._onNuxtLoaded(_app)
  342. }
  343. // Add router hooks
  344. router.afterEach(function (to, from) {
  345. // Wait for fixPrepatch + $data updates
  346. Vue.nextTick(() => _app.$nuxt.$emit('routeChanged', to, from))
  347. })
  348. }
  349. async function mountApp(__app) {
  350. // Set global variables
  351. app = __app.app
  352. router = __app.router
  353. store = __app.store
  354. // Resolve route components
  355. const Components = await Promise.all(resolveComponents(router))
  356. // Create Vue instance
  357. const _app = new Vue(app)
  358. // Load layout
  359. const layout = NUXT.layout || 'default'
  360. await _app.loadLayout(layout)
  361. _app.setLayout(layout)
  362. // Mounts Vue app to DOM element
  363. const mount = () => {
  364. _app.$mount('#__nuxt')
  365. // Listen for first Vue update
  366. Vue.nextTick(() => {
  367. // Call window.onNuxtReady callbacks
  368. nuxtReady(_app)
  369. })
  370. }
  371. // Enable transitions
  372. _app.setTransitions = _app.$options.nuxt.setTransitions.bind(_app)
  373. if (Components.length) {
  374. _app.setTransitions(mapTransitions(Components, router.currentRoute))
  375. _lastPaths = router.currentRoute.matched.map(route => compile(route.path)(router.currentRoute.params))
  376. }
  377. // Initialize error handler
  378. _app.$loading = {} // To avoid error while _app.$nuxt does not exist
  379. if (NUXT.error) _app.error(NUXT.error)
  380. // Add router hooks
  381. router.beforeEach(loadAsyncComponents.bind(_app))
  382. router.beforeEach(render.bind(_app))
  383. router.afterEach(normalizeComponents)
  384. router.afterEach(fixPrepatch.bind(_app))
  385. // If page already is server rendered
  386. if (NUXT.serverRendered) {
  387. mount()
  388. return
  389. }
  390. // First render on client-side
  391. render.call(_app, router.currentRoute, router.currentRoute, (path) => {
  392. // If not redirected
  393. if (!path) {
  394. normalizeComponents(router.currentRoute, router.currentRoute)
  395. showNextPage.call(_app, router.currentRoute)
  396. // Dont call fixPrepatch.call(_app, router.currentRoute, router.currentRoute) since it's first render
  397. mount()
  398. return
  399. }
  400. // Push the path and then mount app
  401. router.push(path, () => mount(), (err) => {
  402. if (!err) return mount()
  403. console.error(err)
  404. })
  405. })
  406. }