未调用 Nuxt 自定义模块挂钩
Nuxt custom module hooks not called
我想从中间件 运行 之后存在的 ssr 服务器传递一些额外数据,并在客户端中间件上使用这些数据。有点类似于 nuxt 已经用 vuex 做的事情。
Documentation 在 render:context
挂钩处:
Every time a route is server-rendered and before render:route hook. Called before serializing Nuxt context into window.__NUXT__, useful to add some data that you can fetch on client-side.
现在我的自定义插件定义了一些钩子,如文档中所述,但似乎并没有被正确调用:
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.
我想从中间件 运行 之后存在的 ssr 服务器传递一些额外数据,并在客户端中间件上使用这些数据。有点类似于 nuxt 已经用 vuex 做的事情。
Documentation 在 render:context
挂钩处:
Every time a route is server-rendered and before render:route hook. Called before serializing Nuxt context into window.__NUXT__, useful to add some data that you can fetch on client-side.
现在我的自定义插件定义了一些钩子,如文档中所述,但似乎并没有被正确调用:
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.