UNPKG

nuxt

Version:

Nuxt is a free and open-source framework with an intuitive and extendable way to create type-safe, performant and production-grade full-stack web applications and websites with Vue.js.

77 lines (76 loc) 2.77 kB
import { getNuxtAppCtx, useNuxtApp } from "../nuxt.js"; import { useRoute } from "./router.js"; import { createError } from "./error.js"; import { hashKey } from "../utils/hash.js"; import { useHead } from "../../head/runtime/composables.js"; import "./head.js"; import { dataDiagnostics } from "../diagnostics/data.js"; import { useAsyncData } from "./asyncData.js"; import { computed, getCurrentInstance } from "vue"; //#region src/app/composables/component.ts const NuxtComponentIndicator = "__nuxt_component"; /* @__NO_SIDE_EFFECTS__ */ function getFetchKey() { const vm = getCurrentInstance(); const route = useRoute(); const { _fetchKeyBase } = vm.proxy.$options; return hashKey([ _fetchKeyBase, route.path, route.query, route.matched.findIndex((r) => Object.values(r.components || {}).includes(vm.type)) ]); } async function runLegacyAsyncData(res, fn) { const nuxtApp = useNuxtApp(); const { fetchKey } = getCurrentInstance().proxy.$options; const { data, error } = await useAsyncData(`options:asyncdata:${(typeof fetchKey === "function" ? fetchKey(() => "") : fetchKey) || /* @__PURE__ */ getFetchKey()}`, () => import.meta.server ? nuxtApp.runWithContext(() => fn(nuxtApp)) : fn(nuxtApp)); if (error.value) throw createError(error.value); if (data.value && typeof data.value === "object") { const _res = await res; for (const key in data.value) _res[key] = computed({ get: () => data.value?.[key], set(v) { data.value = data.value ? { ...data.value, [key]: v } : { [key]: v }; } }); } else if (import.meta.dev) dataDiagnostics.NUXT_E3007({ cause: data }); } /** @since 3.0.0 */ const defineNuxtComponent = /* @__NO_SIDE_EFFECTS__ */ function defineNuxtComponent(...args) { const [options, key] = args; const { setup } = options; if (!setup && !options.asyncData && !options.head) return { [NuxtComponentIndicator]: true, ...options }; return { [NuxtComponentIndicator]: true, _fetchKeyBase: key, ...options, setup(props, ctx) { const nuxtApp = useNuxtApp(); let res = {}; if (setup) { const fn = () => Promise.resolve(setup(props, ctx)).then((r) => r || {}); const nuxtAppCtx = getNuxtAppCtx(nuxtApp._id); if (import.meta.server) res = nuxtAppCtx.callAsync(nuxtApp, fn); else { nuxtAppCtx.set(nuxtApp); res = fn(); } } const promises = []; if (options.asyncData) promises.push(runLegacyAsyncData(res, options.asyncData)); if (options.head) useHead(typeof options.head === "function" ? () => options.head(nuxtApp) : options.head); return Promise.resolve(res).then(() => Promise.all(promises)).then(() => res).finally(() => { promises.length = 0; }); } }; }; //#endregion export { NuxtComponentIndicator, defineNuxtComponent };