Mar*_*ger 15 javascript vue.js nuxt.js nuxtjs
当我为 StackOverflow写这个答案时,我遇到了一个问题,即我想在服务器启动时(或服务器启动时)在 Nuxt.js 中执行一次某些代码。
我想过编写一个模块或插件,但没有成功,因为每次我联系服务器时,即每次调用localhost:3000/myPage时,都会执行这两个模块或插件。可能我缺少正确的模块挂钩或某些插件设置?
由于我在官方文档中找不到有关此问题的任何信息,因此我现在想出了一个相当丑陋的解决方案:我编写了一个服务器中间件,它执行一些代码(应该只运行一次的代码),然后返回一个空处理程序 -现在,这为每个请求增加了(少量)不必要的开销。
我的问题:在启动期间/启动后而不是在构建期间在 Nuxt.js 服务器上执行一次某些代码的最佳方法是什么?
最小的丑陋工作示例:
nuxt.config.js:
export default {
...
serverMiddleware: [ "~/serverMiddleware/run-once.js" ]
...
}
Run Code Online (Sandbox Code Playgroud)
~/serverMiddleware/run-once.js:
console.log("Yay, I only run once when the server is started!")
// Since we are a serverMiddleware, we have to return a handler, even if this it does nothing
// I think this is really ugly...
export default function (req, res, next) {
next()
}
Run Code Online (Sandbox Code Playgroud)
PS:我看到诸如Nuxt JS 插件是否可以只运行一次?但它似乎没有回答我的问题,因为vue-renderer:ssr:prepareContext每次我向服务器发送请求时 nuxt 钩子也会执行。
此外,如下所示的模块不起作用,因为它也在 or 期间执行nuxt build,而不仅仅是在nuxt devor期间执行nuxt start:
export default function MyModuleThatShouldOnlyRunOnce (_moduleOptions) {
console.log("I run on 'nuxt dev' and 'nuxt start', but sadly also on 'nuxt build' :(");
}
Run Code Online (Sandbox Code Playgroud)
小智 0
我不知道这个主题是否仍然相关,但是您可以使用“ready”钩子来解决这个问题:
首先创建一个像这样的文件(./hooks/hooks.js):
export default (nuxtConfig) => ({
ready: () => {
// Execute your code here
}
});
Run Code Online (Sandbox Code Playgroud)
然后将其添加到您的 nuxt.config.js 中:
import hooks from './hooks/hooks';
export default {
// Other stuff
hooks: hooks(this),
// Other stuff
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4566 次 |
| 最近记录: |