English 中文(简体)
如何在Nuxt 3开办的服务器中选取数据?
原标题:How to fetch data as part of server start up in Nuxt 3?

我在Nuxt 3上有一个网络,正在从Nuxt 2迁移。 我们还有一份附录,处理数据库的所有数据检索。 在开始网络服务器时,从该软件中可以发现一个有某种环境(启动所需资金和一些固定变量作为操作时间段)的“焦耳”物体。 在每个部署阶段,这些数值可能有所不同,只有在更新了APIC和App(两者都需要重新启动)。 我不想在用户每当进入时就把这一数据推向一种假想,因为这一呼吁总是产生同样的结果。 目前的“Nuxt 2”会议认为:

// nuxt.config.js (Nuxt 2)

export default async () => {
   const result = await someAsyncCall()

   return {
      // actual config, use result in runtime parameters here, exposed under this.$config
   }
}

根据移民指南() 这种工作方式现已在Nuxt 3中被解释,它建议使用Nuxt hooks,但我找不到实现这一目标的正确途径。 目标是一开始即获得这一json数据,并提供这一数据供各地使用。 我尝试了以下做法:

// This is the Nuxt 3 equivalent, but it s deprecated and for some reason it calls the data twice:

// nuxt.config.ts

export default async () => { 
  const result = await someAsyncCall()

  return defineNuxtConfig({
     runtimeConfig:{
        // use result here
     }
  })
}

// This doesn t update the runtime config

//nuxt.config.ts

export default defineNuxtConfig({
    runtimeConfig: {
      public: {
         myparam:   
      }
    },
    hooks: {
      ready: async (nuxt) => { // not sure if  ready  is available at deploy since it s a build hook anyway
        console.log( READY )
        const settings = await getRuntimeConfig()
        nuxt.options.runtimeConfig.public.myparam = settings
      }
    },
})

// It s not allowed to import from nuxt.config.ts so this doesn t work.

// nuxt.config.ts

export const settings = {}

export default defineNuxtConfig({
    hooks: {
      ready: async (nuxt) => {
        console.log( READY )
        const _settings = await getRuntimeConfig()
        settings = _settings
      }
    },
})

// myPlugin.ts
import { settings } from  nuxt.config  // not allowed

export default defineNuxtPlugin(() => {
  return { provide: { settings } }
})

我还检查了。 但似乎毫无道理。 我如何能够取得预期结果?

最佳回答

A cascade of Nuxt 3/UnJS features must be used to achieve this.

Nuxt 3使用独一无二的处方,因此不需要额外的包裹。

http://www.ohchr.org。 用户开始与用户进行交流时,从外部的APIConce查询数据。

1. Create a Nitro plugin

www.un.org/Depts/DGACM/index_spanish.htm 硝酸 p是自动注册的(档案名称订购),在第一个氮初始化上同步运行。 即使在没有客户的情况下,当服务器开始时,我还是能够使用一个原始数据。 利用储存层(带有记忆动力)在尼特提供数据。

Nuxt 3 Server Plugin Docs - Nitro Plugin Docs - Nitro Storage Layer Docs

// /server/plugins/01.fetchSettings.ts

import { useLogger } from  @nuxt/kit 
import type { Settings } from  @/types/api 

export default defineNitroPlugin(async () => {
  const storage = useStorage( SOME_KEY )
  const consola = useLogger()

  const endpoint = useRuntimeConfig().settingsEndpoint

  async function fetchSettings() {
    consola.start( Fetching settings... )

    const result = await $fetch<Settings>(endpoint)
    await storage.setItem<Settings>( settings , result)

    consola.success(`Settings fetched succesfully!`)
  }
  try {
    fetchSettings()
  } catch (e) {
    consola.error( Error fetching settings. )
    // Error handling here
  }
})


2. Create a "bridge" between Nitro and Nuxt to pass the data using an API route

首先,我试图在操作时间参数上添加APIC号呼吁的结果,但。 我们还不能使用<条码>在我们项目的“应用”部分上的使用<>代码>。

www.un.org/Depts/DGACM/index_spanish.htm 这意味着,我们需要在<代码>/server/api/上建立一个作为桥梁的APIC/strong>通道。 Don t worry: ,但<条码>也予以罚款。 确保对https://nitro.unjs.io/guide/cache#options” rel=“nofollow noreferer”>options , 如果你使用的话。

Nuxt服务器航道:

// /server/api/settings.ts

import type { Settings } from  @/types/api 

export default cachedEventHandler(async () => {
  return await useStorage( SOME_KEY ).getItem<Settings>( settings )
})

3. Create a Nuxt plugin

www.un.org/Depts/DGACM/index_spanish.htm 这里,我们提供一名助手,以回报APIC/S.路面的价值。 自我们使用<条码> 用户代码后,使用<条码>。 我们赢得了实际上履行吉大港山区的请求。 我们把氮路线直接称作功能,因为这一路线出现在服务器上。

Nuxt plugin docs

// /plugins/01.injectSettings.ts

export default defineNuxtPlugin(async () => {
  const asyncData = await useFetch( /api/settings )

  return {
    provide: {
      settings: asyncData.data.value
    }
  }
})


4. Access settings from your app

<template>
    <div>{{ $settings }}</div>
</template>

<script lang="ts" setup>
    // Only required if you use the settings inside <script>
    const { $settings } = useNuxtApp()
</script>

EDIT2:最后回答。

问题回答

You re looking to make a custom Nuxt 3 module

The Nuxt 3 plugins will only work during runtime and modules are now build time only.

我认为,这段话可以解决你的问题:

Here is an example of how I was able to achieve this (I m using Nuxt v3.6.1):

import {
    defineNuxtModule,
    useLogger,
    createResolver,
    addImportsDir,
    addRouteMiddleware,
    addTypeTemplate,
} from  nuxt/kit 
import { $fetch } from  ofetch 

export default defineNuxtModule({
    meta: {
        // Usually the npm package name of your module
        name:  @nuxtjs/my-module ,
        // The key in `nuxt.config` that holds your module options
        configKey:  my-module ,
        // Compatibility constraints
        compatibility: {
            // Semver version of supported nuxt versions
            nuxt:  ^3.6.1 ,
        },
    },

    defaults: {
        // Your Defuault Options
    },
    async setup(options, nuxt) {
        // Create the path resolver
        const resolver = createResolver(import.meta.url)

        // Create the consola logger
        const logger = useLogger( my-module )
        logger.start( Starting... )


        const URL = `some-api/endpoint`
        const data = await $fetch<ResponseType>(URL) // I type my responses
        if (data) { //! I don t know what your response is going to look like
            // You could put these in public or merge existing ones with defu from unjs
            nuxt.options.runtimeConfig.options.myModuleOptions = data
            logger.success( Successfuly Loaded! )
        }
        
        //* Add Feature Specific Composables
        addImportsDir(resolver.resolve( runtime/composables ))

        //* Add Feature Specific Middleware
        addRouteMiddleware({
            name:  myModuleMiddleware ,
            path: resolver.resolve( runtime/middleware/someMiddleware ),
            global: true,
        })

        //* Add the Feature Specific Types
        addTypeTemplate({
            filename:  types/my-module-types.d.ts ,
            src: resolver.resolve( runtime/types.ts ),
            write: true,
        })
    },
})

在Nuxt 3中,对周围的类型模板或中层设备实际上没有很多文件,因此我希望能够帮助某人。





相关问题
Nuxt 3 useRoute import cannot find

I am using latest nuxt version and when I tried to use the useRoute method is triggers a "Cannot Find name useRoute" but it works so I would like to know what could I be missing My package ...

Vue array dependent select not display data

I have dependent selection like this. Selection image when i console log, they have data but not render data in selection data This is what i ve tried. for Product selection has default selected value ...

How to inject Bearer Token in Axios boot file

Quasar has a different setup using boot files and my current axios.ts looks liek this: import { boot } from quasar/wrappers ; import axios, { AxiosInstance } from axios ; declare module @vue/...

Vue router and Vite Base url conflict

I use Vue Router to develop my single page application and use Vite to package my project. I want to deploy all static files (such as index.js and index.css) under another CDN domain name (cdn.example....

Vue.js change class on mounted

I have a button element with a .hover property and I need the hover animation to also happen as soon as the page is mounted. How can I attribute a class to a button on the mounted function and then ...

Laravel +Vuejs CORS issue

I am facing a dilemma wit the CORS issue. I have application that is configured as follow: API: https://abc.mydomain.com (laravel) front end: https://subdomain.mydomain.com(VueJS) Both applications ...