未调用Nuxt自定义模块挂钩

问题描述 投票:1回答:1

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

Documentationrender:context

每次路由是服务器渲染时和渲染之前:路由挂钩。在将Nuxt上下文序列化为窗口.__ 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数据传递给客户端渲染器?

vuejs2 nuxt.js ssr
1个回答
3
投票

好的,刚刚找到了将自定义数据从(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

© www.soinside.com 2019 - 2024. All rights reserved.