有什么区别 1) nuxtServer初始化 2)中间件 3) 插件
什么时候在服务器端处理,什么时候在客户端处理。
最佳答案
If the action nuxtServerInit is defined in the store, Nuxt.js will call it with the context (only from the server-side). It's useful when we have some data on the server we want to give directly to the client-side.
In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes. In SPA mode, middlewares will be called client-side on the first request and when navigating to further routes.
Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root Vue.js Application.
对于未直接提及的插件,需要记住的一件有趣的事情是,它们在服务器上调用一次,在客户端上调用一次(除非您以其他方式配置它们)。
那么现在开始讨论差异。
NuxtServerInit 是这 3 个中最独特的一个。它的用例非常清晰:用服务器上可用的数据填充 Vuex 存储。这非常适合使用一些特定于 session 的数据来设置商店。
插件和中间件之间的区别实际上归结为两件事:
中间件始终在页面导航之间运行,并将在服务器上为第一个路由调用,然后在用户之后进行的每个导航的客户端上调用。这使得它非常适合执行检查页面之间的身份验证等操作。
插件(默认情况下)在服务器和客户端上运行,但重要的是要记住它们只在客户端上运行一次(除非您刷新)。这使得它们非常适合导入和设置库,这些库可以添加到 Nuxt 实例中。
插件也在创建 Nuxt 实例之前运行,这意味着您不能使用 this
访问 Nuxt。这应该进一步说明插件通常应该用于配置和加载依赖项的观点。显然,这是过于简单化了,也有异常(exception),但这应该是一个很好的起点。
当您开始深入研究 Nuxt 时,您会发现这些差异会变得非常模糊,并且发现这 3 种中的每一种在技术上都可以做其他人可以做的几乎所有事情。请务必考虑要解决的问题,然后选择对您最有意义的工具。
关于nuxt.js - Nuxt : Difference nuxtServerInit vs Mddleware vs Plugin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59292838/