2021-06-30 10:53:10 +00:00
|
|
|
import { toRefs } from '@vue/reactivity'
|
2021-08-09 16:18:21 +00:00
|
|
|
import { defineComponent, getCurrentInstance } 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'
|
2021-11-15 10:25:50 +00:00
|
|
|
import type { LegacyContext } from '../compat/legacy-app'
|
2021-08-27 13:30:53 +00:00
|
|
|
import { 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'
|
|
|
|
|
2021-06-30 10:53:10 +00:00
|
|
|
async function runLegacyAsyncData (res: Record<string, any> | Promise<Record<string, any>>, fn: (context: LegacyContext) => 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
|
2021-10-08 14:21:55 +00:00
|
|
|
const { data } = await useAsyncData(`options:asyncdata:${key}`, () => fn(nuxt._legacyContext))
|
2021-06-30 10:53:10 +00:00
|
|
|
Object.assign(await res, toRefs(data))
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|