fetch.server.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import Vue from 'vue'
  2. import { hasFetch, normalizeError, addLifecycleHook, purifyData, createGetCounter } from '../utils'
  3. async function serverPrefetch() {
  4. if (!this._fetchOnServer) {
  5. return
  6. }
  7. // Call and await on $fetch
  8. try {
  9. await this.$options.fetch.call(this)
  10. } catch (err) {
  11. if (process.dev) {
  12. console.error('Error in fetch():', err)
  13. }
  14. this.$fetchState.error = normalizeError(err)
  15. }
  16. this.$fetchState.pending = false
  17. // Define an ssrKey for hydration
  18. this._fetchKey = this._fetchKey || this.$ssrContext.fetchCounters['']++
  19. // Add data-fetch-key on parent element of Component
  20. const attrs = this.$vnode.data.attrs = this.$vnode.data.attrs || {}
  21. attrs['data-fetch-key'] = this._fetchKey
  22. // Add to ssrContext for window.__NUXT__.fetch
  23. if (this.$ssrContext.nuxt.fetch[this._fetchKey] !== undefined) {
  24. console.warn(`Duplicate fetch key detected (${this._fetchKey}). This may lead to unexpected results.`)
  25. }
  26. this.$ssrContext.nuxt.fetch[this._fetchKey] =
  27. this.$fetchState.error ? { _error: this.$fetchState.error } : purifyData(this._data)
  28. }
  29. export default {
  30. created() {
  31. if (!hasFetch(this)) {
  32. return
  33. }
  34. if (typeof this.$options.fetchOnServer === 'function') {
  35. this._fetchOnServer = this.$options.fetchOnServer.call(this) !== false
  36. } else {
  37. this._fetchOnServer = this.$options.fetchOnServer !== false
  38. }
  39. const defaultKey = this.$options._scopeId || this.$options.name || ''
  40. const getCounter = createGetCounter(this.$ssrContext.fetchCounters, defaultKey)
  41. if (typeof this.$options.fetchKey === 'function') {
  42. this._fetchKey = this.$options.fetchKey.call(this, getCounter)
  43. } else {
  44. const key = 'string' === typeof this.$options.fetchKey ? this.$options.fetchKey : defaultKey
  45. this._fetchKey = key ? key + ':' + getCounter(key) : String(getCounter(key))
  46. }
  47. // Added for remove vue undefined warning while ssr
  48. this.$fetch = () => {} // issue #8043
  49. Vue.util.defineReactive(this, '$fetchState', {
  50. pending: true,
  51. error: null,
  52. timestamp: Date.now()
  53. })
  54. addLifecycleHook(this, 'serverPrefetch', serverPrefetch)
  55. }
  56. }