Nuxt 自定义模块挂钩未调用

Ray*_*dus 2 server-side-rendering vuejs2 nuxt.js

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

挂钩处的文档render:context

每次路由被服务器渲染并且在 render:route hook 之前。在将 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')
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Ray*_*dus 5

好的,刚刚找到了将自定义数据从(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)
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的中注册插件nuxt.config.js

module.exports = {
  plugins: ['~/plugins/my-plugin']
}
Run Code Online (Sandbox Code Playgroud)

文档在这里