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

hooks 属性

钩子是 Nuxt 事件监听器 ,通常在 Nuxt 模块中使用,也可在 nuxt.config.js 中使用。


  • 类型: Object
nuxt.config.js
import fs from 'fs'
import path from 'path'

export default {
  hooks: {
    build: {
      done(builder) {
        const extraFilePath = path.join(
          builder.nuxt.options.buildDir,
          'extra-file'
        )
        fs.writeFileSync(extraFilePath, 'Something extra')
      }
    }
  }
}

在内部,钩子遵循使用冒号的命名模式(如 build:done)。为了便于配置,如上例所示,在 nuxt.config.js 中配置自定义钩子时,可以将它们结构化为层级对象。有关工作原理的更多详情,请参阅 Nuxt 内部

钩子列表

示例

非根路径时重定向到 router.base

假设要将页面提供为 /portal 而不是 /

这可能是一个边缘情况,nuxt.config.jsrouter.base 的作用是当 Web 服务器在域根以外的位置提供 Nuxt 时使用。

但在本地开发时,访问 localhost 时如果 router.base 不是 / 会返回 404。可以通过设置钩子来避免这种情况。

重定向对于生产网站可能不是最佳用例,但有助于利用钩子。

首先,可以更改 router.base ,更新 nuxt.config.js

nuxt.config.js
import hooks from './hooks'
export default {
  router: {
    base: '/portal'
  }
  hooks: hooks(this)
}

然后创建几个文件:

  1. 钩子模块 hooks/index.js
    hooks/index.js
    import render from './render'
    
    export default nuxtConfig => ({
      render: render(nuxtConfig)
    })
    
  2. 渲染钩子 hooks/render.js
    hooks/render.js
    import redirectRootToPortal from './route-redirect-portal'
    
    export default nuxtConfig => {
      const router = Reflect.has(nuxtConfig, 'router') ? nuxtConfig.router : {}
      const base = Reflect.has(router, 'base') ? router.base : '/portal'
    
      return {
        /**
         * 'render:setupMiddleware'
         * {@link node_modules/nuxt/lib/core/renderer.js}
         */
        setupMiddleware(app) {
          app.use('/', redirectRootToPortal(base))
        }
      }
    }
    
  3. 中间件本身 hooks/route-redirect-portal.js
    hooks/route-redirect-portal.js
    /**
     * 从 / 重定向到 /portal 的 Nuxt 中间件钩子(或 nuxt.config.js 中 router.base 配置的路径)
     *
     * 请与 connect 保持相同版本
     * {@link node_modules/connect/package.json}
     */
    import parseurl from 'parseurl'
    
    /**
     * 连接中间件,处理重定向到目标 Web 应用程序上下文根。
     *
     * 注意 Nuxt 文档中缺少钩子使用说明
     * 这是一个有用的路由示例作为补充说明。
     *
     * 参考优秀实现:
     * - https://github.com/nuxt/nuxt/blob/2.x-dev/examples/with-cookies/plugins/cookies.js
     * - https://github.com/yyx990803/launch-editor/blob/master/packages/launch-editor-middleware/index.js
     *
     * [http_class_http_clientrequest]: https://nodejs.org/api/http.html#http_class_http_clientrequest
     * [http_class_http_serverresponse]: https://nodejs.org/api/http.html#http_class_http_serverresponse
     *
     * @param {http.ClientRequest} req Node.js 内部客户端请求对象 [http_class_http_clientrequest]
     * @param {http.ServerResponse} res Node.js 内部响应 [http_class_http_serverresponse]
     * @param {Function} next 中间件回调
     */
    export default desiredContextRoot =>
      function projectHooksRouteRedirectPortal(req, res, next) {
        const desiredContextRootRegExp = new RegExp(`^${desiredContextRoot}`)
        const _parsedUrl = Reflect.has(req, '_parsedUrl') ? req._parsedUrl : null
        const url = _parsedUrl !== null ? _parsedUrl : parseurl(req)
        const startsWithDesired = desiredContextRootRegExp.test(url.pathname)
        const isNotProperContextRoot = desiredContextRoot !== url.pathname
        if (isNotProperContextRoot && startsWithDesired === false) {
          const pathname = url.pathname === null ? '' : url.pathname
          const search = url.search === null ? '' : url.search
          const Location = desiredContextRoot + pathname + search
          res.writeHead(302, {
            Location
          })
          res.end()
        }
        next()
      }
    

这样,当开发中的 Web 服务同事误访问 / 时,Nuxt 会自动重定向到 /portal

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