简体   繁体   English

Nuxt - 如何在服务器端渲染后在客户端运行代码?

[英]Nuxt - How can I run a code in client-side after server-side-rendering?

I created a plugin injecting a noty ( https://ned.im/noty/#/ ) so I can use it globally, it looks like this:我创建了一个注入 noty ( https://ned.im/noty/#/ ) 的插件,所以我可以在全球范围内使用它,它看起来像这样:

export default ({ app }, inject) => {

    const notify = function (options = {}) {
        if (process.client) {
            new Noty(options).show();
        }
    }

    app.$notify = notify;
    inject('notify', notify);

}

This plugin shows a noty only on the client-side.这个插件只在客户端显示一个noty。 On the server-side a noty does not appear, cause it can be displayed only in browser.在服务器端没有出现noty,因为它只能在浏览器中显示。 I have a page with product details and I am receiving data in asyncData method.我有一个包含产品详细信息的页面,我正在使用 asyncData 方法接收数据。 When the product was not found I would like to show a noty with proper message and redirect user to a product list page.当找不到产品时,我想显示带有正确消息的通知并将用户重定向到产品列表页面。 When I change a route in client-side everything works awesome.当我在客户端更改路线时,一切都很棒。 However on the first page load (eg. I change an url manually in the browser) which happens on the server-side a noty does not appear, only a redirect works.然而,在服务器端发生的第一页加载(例如,我在浏览器中手动更改了一个 url)时,不会出现通知,只有重定向有效。 My question is: how to show a noty in this case?我的问题是:在这种情况下如何显示通知? How to create a noty in the browser after SSR or what is the best other solution to my problem?如何在 SSR 之后在浏览器中创建通知或解决我的问题的最佳其他解决方案是什么?

Is there any way to run some code after client-side is already rendered (after server-side-rendering)?有没有办法在客户端已经呈现之后(在服务器端呈现之后)运行一些代码?

You could just disable ssr for that plugin.您可以为该插件禁用 ssr。

plugins: [
   ...,
   { src: '~plugins/yourplugin.js', ssr: false }
]

好的,我找到了一个模块: https : //github.com/potato4d/nuxt-client-init-module

it's not possible right know (nuxt <= 2.14.0 when i answering) but you can combine client plugin and client middleware to achieve that please take a look at this link:不可能正确知道(当我回答时nuxt <= 2.14.0)但您可以结合客户端插件和客户端中间件来实现这一点,请查看此链接:

https://github.com/nuxt/nuxt.js/issues/2653#issuecomment-390588837 https://github.com/nuxt/nuxt.js/issues/2653#issuecomment-390588837

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM