【问题标题】:Nuxt custom module hooks not called未调用 Nuxt 自定义模块挂钩
【发布时间】:2018-09-11 23:00:43
【问题描述】:

我想在中间件运行后从 ssr 服务器传递一些额外的数据,并在客户端中间件上使用它。有点类似于 nuxt 已经对 vuex 所做的事情。

Documentation render:context 钩子:

每次路由被服务器渲染并且在 render:route 钩子之前。在将 Nuxt 上下文序列化到 window.__NUXT__ 之前调用,对于添加一些可以在客户端获取的数据很有用。

现在我的自定义插件定义了文档中所述的一些钩子,但似乎并非所有钩子都被正确调用:

module.exports = function() {
  this.nuxt.hook('render:route', (url, result, context) => {
    console.log('This one is called on every server side rendering')
  }

  this.nuxt.hook('renderer', renderer => {
    console.log('This is never called')
  }

  this.nuxt.hook('render:context', context => {
    console.log('This is only called once, when it starts loading the module')
  }
}

我做错了什么,如何将自定义 ssr 数据传递给客户端渲染器?

【问题讨论】:

  • 你用的是哪个nuxt版本?
  • 我使用的是 1.4.0
  • 只是为了测试,您可以在nuxt-edge 的最小示例中尝试这个吗?
  • 我试过了,但我一直收到与此处状态相同的错误:stackoverflow.com/questions/51716353

标签: vuejs2 nuxt.js server-side-rendering


【解决方案1】:

好的,刚刚找到将自定义数据从(ssr)服务器传递到客户端的核心问题的解决方案:

创建插件:plugins/my-plugin.js

export default ({ beforeNuxtRender, nuxtState }) => {
  if (process.server) {
    beforeNuxtRender(({ nuxtState }) => {
      nuxtState.myCustomData = true
    })
  } else {
    console.log('My cystom data on the client side:', nuxtState.myCustomData)
  }
}

然后在你的nuxt.config.js注册插件:

module.exports = {
  plugins: ['~/plugins/my-plugin']
}

文档here.

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2018-08-04
    • 2020-01-23
    相关资源
    最近更新 更多