2022-01-11 17:41:55 +00:00
|
|
|
import { defineComponent, getCurrentInstance, reactive, toRefs } from 'vue'
|
2021-09-30 18:19:55 +00:00
|
|
|
import type { DefineComponent } from 'vue'
|
2021-06-30 10:53:10 +00:00
|
|
|
import { useRoute } from 'vue-router'
|
2022-07-06 19:15:00 +00:00
|
|
|
import { NuxtApp, useNuxtApp } from '../nuxt'
|
2021-10-08 14:21:55 +00:00
|
|
|
import { useAsyncData } from './asyncData'
|
2021-04-03 10:03:20 +00:00
|
|
|
|
|
|
|
export const NuxtComponentIndicator = '__nuxt_component'
|
|
|
|
|
2022-07-06 19:15:00 +00:00
|
|
|
async function runLegacyAsyncData (res: Record<string, any> | Promise<Record<string, any>>, fn: (nuxtApp: NuxtApp) => Promise<Record<string, any>>) {
|
2021-08-27 13:30:53 +00:00
|
|
|
const nuxt = useNuxtApp()
|
2021-06-30 10:53:10 +00:00
|
|
|
const route = useRoute()
|
2021-09-30 18:19:55 +00:00
|
|
|
const vm = getCurrentInstance()
|
2021-06-30 10:53:10 +00:00
|
|
|
const { fetchKey } = vm.proxy.$options
|
|
|
|
const key = typeof fetchKey === 'function' ? fetchKey(() => '') : fetchKey || route.fullPath
|
2022-07-06 19:15:00 +00:00
|
|
|
const { data } = await useAsyncData(`options:asyncdata:${key}`, () => fn(nuxt))
|
2022-01-11 17:41:55 +00:00
|
|
|
if (data.value && typeof data.value === 'object') {
|
|
|
|
Object.assign(await res, toRefs(reactive(data.value)))
|
|
|
|
} else if (process.dev) {
|
|
|
|
console.warn('[nuxt] asyncData should return an object', data)
|
|
|
|
}
|
2021-06-30 10:53:10 +00:00
|
|
|
}
|
|
|
|
|
2021-04-03 10:03:20 +00:00
|
|
|
export const defineNuxtComponent: typeof defineComponent =
|
|
|
|
function defineNuxtComponent (options: any): any {
|
|
|
|
const { setup } = options
|
|
|
|
|
2021-09-30 18:19:55 +00:00
|
|
|
// Avoid wrapping if no options api is used
|
2021-06-30 10:53:10 +00:00
|
|
|
if (!setup && !options.asyncData) {
|
2021-04-03 10:03:20 +00:00
|
|
|
return {
|
|
|
|
[NuxtComponentIndicator]: true,
|
|
|
|
...options
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
[NuxtComponentIndicator]: true,
|
|
|
|
...options,
|
|
|
|
setup (props, ctx) {
|
2021-06-30 10:53:10 +00:00
|
|
|
const res = setup?.(props, ctx) || {}
|
|
|
|
|
2021-09-30 18:19:55 +00:00
|
|
|
let promises: unknown[] | undefined = []
|
|
|
|
promises = promises || []
|
2021-06-30 10:53:10 +00:00
|
|
|
if (options.asyncData) {
|
|
|
|
promises.push(runLegacyAsyncData(res, options.asyncData))
|
|
|
|
}
|
2021-04-03 10:03:20 +00:00
|
|
|
|
|
|
|
return Promise.resolve(res)
|
|
|
|
.then(() => Promise.all(promises))
|
|
|
|
.then(() => res)
|
|
|
|
.finally(() => {
|
|
|
|
promises.length = 0
|
|
|
|
promises = null
|
|
|
|
})
|
|
|
|
}
|
|
|
|
} as DefineComponent
|
|
|
|
}
|