NuxtApp
在 Nuxt 中,你可以在组合式函数(composables)、组件和插件内访问运行时应用上下文。
在 Nuxt 中,你可以在组合式函数(composables)、组件和插件内访问运行时应用上下文。
Nuxt 应用接口
Nuxt 上下文
许多组合式函数和工具(无论是内置的还是用户自建的)可能需要访问 Nuxt 实例。它并非在应用程序的任何地方都存在,因为每次请求都会创建一个全新的实例。
目前,Nuxt 上下文仅在 插件、Nuxt 钩子、Nuxt 中间件(如果被 defineNuxtRouteMiddleware 包裹),以及setup 函数(在页面和组件中)中可访问。
如果调用的组合式函数无法访问上下文,你可能会收到一条错误消息,提示“A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function.”。在这种情况下,你可以使用 nuxtApp.runWithContext 在此上下文中显式调用函数。
访问 NuxtApp
在组合式函数、插件和组件中,你可以通过 useNuxtApp() 来访问 nuxtApp。
app/composables/useMyComposable.ts
export function useMyComposable () {
const nuxtApp = useNuxtApp()
// access runtime nuxt app instance
}
如果你的组合式函数并不总是需要 nuxtApp,或者你只想检查它是否存在(由于 useNuxtApp 会抛出异常),你可以改用 tryUseNuxtApp。
为了方便起见,插件也会将 nuxtApp 作为第一个参数接收。
提供辅助工具(Helpers)
你可以提供可在所有组合式函数和应用程序中使用的辅助工具。这通常在 Nuxt 插件中完成。
const nuxtApp = useNuxtApp()
nuxtApp.provide('hello', name => `Hello ${name}!`)
console.log(nuxtApp.$hello('name')) // Prints "Hello name!"