useNuxtApp
useNuxtApp
是一个内置的组合式函数,它提供了一种访问 Nuxt 共享运行时上下文的方法,也称为 Nuxt 上下文,它在客户端和服务器端(但不在 Nitro 路由中)都可用。它帮助你访问 Vue 应用程序实例、运行时钩子、运行时配置变量和内部状态,例如 ssrContext
和 payload
。
<script setup lang="ts">
const nuxtApp = useNuxtApp()
</script>
如果你的作用域中没有运行时上下文,调用 useNuxtApp
将会抛出异常。你可以使用 tryUseNuxtApp
来代替那些不需要 nuxtApp
的组合式函数,或者只是检查上下文是否可用而不抛出异常。
方法
provide (name, value)
nuxtApp
是一个运行时上下文,你可以使用 Nuxt 插件 扩展它。使用 provide
函数创建 Nuxt 插件,使值和辅助方法在你的 Nuxt 应用程序中的所有组合式函数和组件中都可用。
provide
函数接受 name
和 value
参数。
const nuxtApp = useNuxtApp()
nuxtApp.provide('hello', name => `Hello ${name}!`)
// Prints "Hello name!"
console.log(nuxtApp.$hello('name'))
如上例所示,$hello
已成为 nuxtApp
上下文的新自定义部分,并且在所有可以访问 nuxtApp
的地方都可用。
hook(name, cb)
nuxtApp
中可用的钩子允许你自定义 Nuxt 应用程序的运行时方面。你可以在 Vue.js 组合式函数和 Nuxt 插件 中使用运行时钩子来挂接到渲染生命周期。
hook
函数对于在特定点通过挂接到渲染生命周期来添加自定义逻辑非常有用。hook
函数主要用于创建 Nuxt 插件。
请参阅 运行时钩子 以了解 Nuxt 调用的可用运行时钩子。
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('page:start', () => {
/* your code goes here */
})
nuxtApp.hook('vue:error', (..._args) => {
console.log('vue:error')
// if (import.meta.client) {
// console.log(..._args)
// }
})
})
callHook(name, ...args)
当使用任何现有钩子调用时,callHook
会返回一个 Promise。
await nuxtApp.callHook('my-plugin:init')
属性
useNuxtApp()
暴露了以下属性,你可以使用它们来扩展和自定义你的应用程序,并共享状态、数据和变量。
vueApp
vueApp
是全局的 Vue.js应用程序实例你可以通过 nuxtApp
访问。
一些有用的方法
component()
- 如果同时传递名称字符串和组件定义,则注册一个全局组件;如果只传递名称,则检索已注册的组件。directive()
- 如果同时传递名称字符串和指令定义,则注册一个全局自定义指令;如果只传递名称,则检索已注册的指令(示例)。use()
- 安装一个**Vue.js 插件** (示例)。
ssrContext
ssrContext
在服务器端渲染期间生成,并且仅在服务器端可用。
Nuxt 通过 ssrContext
暴露以下属性
url
(字符串) - 当前请求 URL。事件
(h3js/h3请求事件) - 访问当前路由的请求和响应。payload
(对象) - NuxtApp 有效载荷对象。
payload
payload
将服务器端的数据和状态变量暴露给客户端。以下键在从服务器端传递后将在客户端可用
serverRendered
(布尔值) - 指示响应是否为服务器端渲染。data
(对象) - 当你使用useFetch
或useAsyncData
从 API 端点获取数据时,结果有效载荷可以通过payload.data
访问。此数据已缓存,可帮助你防止在多次发出相同请求时重复获取相同数据。<script setup lang="ts"> const { data } = await useAsyncData('count', () => $fetch('/api/count')) </script>
export default defineEventHandler((event) => { return { count: 1 } })
在上面的示例中,使用useAsyncData
获取count
的值后,如果你访问payload.data
,你将看到其中记录了{ count: 1 }
。
当从ssrcontext
访问相同的payload.data
时,你也可以在服务器端访问相同的值。state
(对象) - 当你在 Nuxt 中使用useState
组合式函数来设置共享状态时,此状态数据通过payload.state.[name-of-your-state]
访问。app/plugins/my-plugin.tsexport const useColor = () => useState<string>('color', () => 'pink') export default defineNuxtPlugin((nuxtApp) => { if (import.meta.server) { const color = useColor() } })
也可以使用更高级的类型,例如ref
、reactive
、shallowRef
、shallowReactive
和NuxtError
。
自Nuxt v3.4起,可以为 Nuxt 不支持的类型定义自己的 reducer/reviver。
在下面的示例中,我们使用 payload 插件为LuxonDateTime 类定义了一个 reducer(或序列化器)和一个 reviver(或反序列化器)。app/plugins/date-time-payload.ts/** * This kind of plugin runs very early in the Nuxt lifecycle, before we revive the payload. * You will not have access to the router or other Nuxt-injected properties. * * Note that the "DateTime" string is the type identifier and must * be the same on both the reducer and the reviver. */ export default definePayloadPlugin((nuxtApp) => { definePayloadReducer('DateTime', (value) => { return value instanceof DateTime && value.toJSON() }) definePayloadReviver('DateTime', (value) => { return DateTime.fromISO(value) }) })
isHydrating
使用 nuxtApp.isHydrating
(布尔值) 检查 Nuxt 应用程序是否正在客户端进行水合。
export default defineComponent({
setup (_props, { slots, emit }) {
const nuxtApp = useNuxtApp()
onErrorCaptured((err) => {
if (import.meta.client && !nuxtApp.isHydrating) {
// ...
}
})
},
})
runWithContext
runWithContext
方法旨在用于调用函数并为其提供显式的 Nuxt 上下文。通常,Nuxt 上下文是隐式传递的,你不需要担心这一点。但是,在处理中间件/插件中复杂的 async
/await
场景时,你可能会遇到在异步调用后当前实例已被取消设置的情况。
export default defineNuxtRouteMiddleware(async (to, from) => {
const nuxtApp = useNuxtApp()
let user
try {
user = await fetchUser()
// the Vue/Nuxt compiler loses context here because of the try/catch block.
} catch (e) {
user = null
}
if (!user) {
// apply the correct Nuxt context to our `navigateTo` call.
return nuxtApp.runWithContext(() => navigateTo('/auth'))
}
})
使用
const result = nuxtApp.runWithContext(() => functionWithContext())
functionWithContext
:任何需要当前 Nuxt 应用程序上下文的函数。此上下文将自动正确应用。
runWithContext
将返回 functionWithContext
返回的任何值。
上下文的更深层解释
Vue.js 组合式 API(以及类似的 Nuxt 组合式函数)通过依赖隐式上下文工作。在生命周期期间,Vue 将当前组件的临时实例(以及 Nuxt 的 nuxtApp 临时实例)设置为全局变量,并在同一时间点取消设置。在服务器端渲染时,来自不同用户的多个请求和 nuxtApp 在同一个全局上下文中运行。因此,Nuxt 和 Vue 会立即取消设置此全局实例,以避免两个用户或组件之间共享引用泄漏。
这意味着什么?组合式 API 和 Nuxt 组合式函数仅在生命周期和任何异步操作之前的同一时间点可用
// --- Vue internal ---
const _vueInstance = null
const getCurrentInstance = () => _vueInstance
// ---
// Vue / Nuxt sets a global variable referencing to current component in _vueInstance when calling setup()
async function setup () {
getCurrentInstance() // Works
await someAsyncOperation() // Vue unsets the context in same tick before async operation!
getCurrentInstance() // null
}
对此的经典解决方案是在第一次调用时将当前实例缓存到局部变量,例如 const instance = getCurrentInstance()
,并在下一次组合式函数调用中使用它,但问题是任何嵌套的组合式函数调用现在都需要显式接受实例作为参数,而不是依赖于组合式 API 的隐式上下文。这是组合式函数的设计限制,本身不是问题。
为了克服这个限制,Vue 在编译我们的应用程序代码时做了一些幕后工作,并在每次 <script setup>
调用后恢复上下文
const __instance = getCurrentInstance() // Generated by Vue compiler
getCurrentInstance() // Works!
await someAsyncOperation() // Vue unsets the context
__restoreInstance(__instance) // Generated by Vue compiler
getCurrentInstance() // Still works!
有关 Vue 实际操作的更详细描述,请参阅unjs/unctx#2 (comment).
解决方案
这就是 runWithContext
可以用来恢复上下文的地方,类似于 <script setup>
的工作方式。
Nuxt 内部使用unjs/unctx来支持类似于 Vue 的插件和中间件的组合式函数。这使得像 navigateTo()
这样的组合式函数可以在不直接向它们传递 nuxtApp
的情况下工作——将组合式 API 的开发体验和性能优势带到整个 Nuxt 框架。
Nuxt 组合式函数与 Vue 组合式 API 具有相同的设计,因此需要类似的解决方案来“神奇地”实现这种转换。请查看unjs/unctx#2(提案),unjs/unctx#4(转换实现),以及nuxt/framework#3884(集成到 Nuxt)。
Vue 目前只支持 <script setup>
的异步上下文恢复,用于 async/await 用法。在 Nuxt 中,为 defineNuxtPlugin()
和 defineNuxtRouteMiddleware()
添加了转换支持,这意味着当你使用它们时,Nuxt 会自动使用上下文恢复对其进行转换。
剩余问题
在包含 await
的 try/catch
语句中,unjs/unctx
转换自动恢复上下文似乎存在 bug,这最终需要解决,以便消除上述建议的 workaround 的要求。
原生异步上下文
使用一项新的实验性功能,可以通过使用Node.js AsyncLocalStorage
和新的 unctx 支持来启用原生异步上下文支持,使异步上下文原生可用于任何嵌套的异步组合式函数,而无需转换或手动传递/调用上下文。
tryUseNuxtApp
此函数的工作方式与 useNuxtApp
完全相同,但如果上下文不可用,则返回 null
而不是抛出异常。
你可以将其用于不需要 nuxtApp
的组合式函数,或者只是检查上下文是否可用而不抛出异常。
示例用法
export function useStandType () {
// Always works on the client
if (tryUseNuxtApp()) {
return useRuntimeConfig().public.STAND_TYPE
} else {
return process.env.STAND_TYPE
}
}