您正在浏览 Nuxt 2 文档。前往 Nuxt 3 文档, 或了解更多关于 Nuxt 2 长期支持

上下文

context 从 Nuxt 向 Vue 组件提供额外的对象/参数,可在 asyncData fetch plugins middleware 以及 nuxtServerInit 等特殊 Nuxt 生命周期中使用。


注意:请不要将这里的"上下文"与 Vuex 的 action 中可用的 context 对象混淆,两者毫无关联。

function (context) {
  // 通用键
  const {
    app,
    store,
    route,
    params,
    query,
    env,
    isDev,
    isHMR,
    redirect,
    error,
    $config
  } = context
  // 服务端
  if (process.server) {
    const { req, res, beforeNuxtRender } = context
  }
  // 客户端
  if (process.client) {
    const { from, nuxtState } = context
  }
}

通用键

这些键在客户端和服务端均可使用。

app

app (NuxtAppOptions)

包含所有插件的根 Vue 实例选项。例如使用 i18n 时,可通过 context.app.i18n 访问 $i18n

store

store (Vuex Store )

Vuex Store 实例。仅在设置了 Vuex store 时可用

route

route (Vue Router Route )

Vue Router 的路由实例。

params

params (Object)

route.params 的别名。

query

query (Object)

route.query 的别名。

env

env (Object)

nuxt.config.js 中设置的环境变量,参见 env API

isDev

isDev (Boolean)

表示是否处于开发模式的布尔值,可用于在生产环境中缓存部分数据。

isHMR

isHMR (Boolean)

表示方法/中间件是否从 webpack 热模块替换中调用的布尔值(仅在开发模式的客户端为 true)。

redirect

redirect (Function)

使用此方法将用户重定向到另一个路由。状态码在服务端使用,默认为 302redirect([status,] path [, query])

示例:

redirect(302, '/login')
redirect({ name: 'slug', params: { slug: mySlug } })
redirect('https://vuejs.org')

有关 Location 属性的详细信息,请参阅 Vue Router 文档

由于水合错误(客户端内容与服务器返回内容不一致),不能在仅客户端的 Nuxt 插件 中使用 redirecterror。有效的解决方法是使用 window.onNuxtReady(() => { window.$nuxt.$router.push('/your-route') })

error

error (Function)

使用此方法显示错误页面,例如:error(params)params 需要包含 statusCodemessage 属性。

$config

$config (Object)

实际的运行时配置

服务端键

这些键仅在服务端可用。

req

req (http.Request )

来自 Node.js 服务器的请求对象。当 Nuxt 作为中间件使用时,请求对象可能因所用框架而异。
nuxt generate 中不可用。

Res

res (http.Response )

来自 Node.js 服务器的响应对象。当 Nuxt 作为中间件使用时,响应对象可能因所用框架而异。
nuxt generate 中不可用。

beforeNuxtRender

beforeNuxtRender(fn) (Function)

使用此方法更新客户端渲染的 __NUXT__ 变量。fn(可以是异步的)将以 { Components, nuxtState } 调用,参见示例

客户端键

这些键仅在客户端可用。

from

from (Vue Router Route )

来源路由。

nuxtState

nuxtState (Object)

Nuxt 状态。对于在水合前在客户端使用 beforeNuxtRender 获取 Nuxt 状态的插件非常有用。仅在 universal 模式下可用。

Edit this page on GitHub Updated at Tue, Apr 14, 2026