上下文

Nuxt Kit 提供了一组实用程序来帮助你使用上下文。

Nuxt 模块允许你增强 Nuxt 的功能。它们提供了一种结构化的方式来保持代码的井然有序和模块化。如果你想将模块分解为更小的组件,Nuxt 提供了 useNuxttryUseNuxt 函数。这些函数使你能够方便地从上下文访问 Nuxt 实例,而无需将其作为参数传递。

¥Nuxt modules allow you to enhance Nuxt's capabilities. They offer a structured way to keep your code organized and modular. If you're looking to break down your module into smaller components, Nuxt offers the useNuxt and tryUseNuxt functions. These functions enable you to conveniently access the Nuxt instance from the context without having to pass it as argument.

当你在 Nuxt 模块中使用 setup 函数时,Nuxt 已将其作为第二个参数提供。这意味着你可以直接使用它,而无需调用 useNuxt()。你可以参考 Nuxt Site Config 作为使用示例。

useNuxt

获取给定页面的完整 URL(包括测试服务器正在运行的端口。)如果 Nuxt 不可用,它将抛出错误。

¥Get the Nuxt instance from the context. It will throw an error if Nuxt is not available.

类型

¥Type

function useNuxt(): Nuxt

interface Nuxt {
  options: NuxtOptions
  hooks: Hookable<NuxtHooks>
  hook: Nuxt['hooks']['hook']
  callHook: Nuxt['hooks']['callHook']
  addHooks: Nuxt['hooks']['addHooks']
  ready: () => Promise<void>
  close: () => Promise<void>
  server?: any
  vfs: Record<string, string>
  apps: Record<string, NuxtApp>
}

示例

¥Examples

// https://github.com/Lexpeartha/nuxt-xstate/blob/main/src/parts/transpile.ts
import { useNuxt } from '@nuxt/kit'

export const setupTranspilation = () => {
  const nuxt = useNuxt()

  nuxt.options.build.transpile = nuxt.options.build.transpile || []

  if (nuxt.options.builder === '@nuxt/webpack-builder') {
    nuxt.options.build.transpile.push(
      'xstate',
    )
  }
}

tryUseNuxt

获取给定页面的完整 URL(包括测试服务器正在运行的端口。)如果 Nuxt 不可用,它将返回 null

¥Get the Nuxt instance from the context. It will return null if Nuxt is not available.

类型

¥Type

function tryUseNuxt(): Nuxt | null

interface Nuxt {
  options: NuxtOptions
  hooks: Hookable<NuxtHooks>
  hook: Nuxt['hooks']['hook']
  callHook: Nuxt['hooks']['callHook']
  addHooks: Nuxt['hooks']['addHooks']
  ready: () => Promise<void>
  close: () => Promise<void>
  server?: any
  vfs: Record<string, string>
  apps: Record<string, NuxtApp>
}

示例

¥Examples

// https://github.com/harlan-zw/nuxt-site-config/blob/main/test/assertions.test.ts
import { tryUseNuxt } from '@nuxt/kit'

interface SiteConfig {
  title: string
}

export const requireSiteConfig = (): SiteConfig => {
  const nuxt = tryUseNuxt()
  if (!nuxt) {
    return { title: null }
  }
  return nuxt.options.siteConfig
}