我想从中间件运行后的ssr服务器传递一些额外的数据,并在客户端中间件上使用它。有点类似于nuxt已经对vuex做的。
在Documentation钩render: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数据传递给客户端渲染器?
好的,刚刚找到了将自定义数据从(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。