简体   繁体   English

在 Nuxt.js 中渲染之前如何使用 auth.loggedIn?

[英]How to have auth.loggedIn before rendering in Nuxt.js?

The /api/user/ request to make $auth.loggedIn available happens after client already loads/started loading.使$auth.loggedIn可用的/api/user/请求发生在客户端已经加载/开始加载之后。 This makes some of my modules render and then disappear after $auth.loggedIn has turned true/false, making everything look messy on page load.这使得我的一些模块在$auth.loggedIn变为 true/false 后呈现然后消失,使页面加载时一切看起来都很混乱。

It would be ideal if the call to /api/user/ happened in the same way an asyncData request works so that $auth.loggedIn is available before anything renders.如果对/api/user/的调用以与 asyncData 请求相同的方式发生,以便$auth.loggedIn在任何呈现之前可用,那将是理想的。 Is there any setup/config that makes this possible ?是否有任何设置/配置使这成为可能? I'm using the universal mode.我正在使用通用模式。

You can use the middleware defined in Nuxt here In your case you could do your request on /api/user before like that, in a middleware called userLoggedIn for example.您可以在此处使用 Nuxt 中定义的中间件在您的情况下,您可以在/api/user上执行您的请求,例如在名为userLoggedIn的中间件中。

export default function (context) {
    // Here we return a Promise in the middleware to make it asynchronous
    // Cf doc https://nuxtjs.org/guide/routing#middleware
    // So we return a promise that can only be resolved when the function resolve is called
    return new Promise(resolve => this.$axios.$get('/api/user'/).then((user) => {
        if (!user) {
            console.log('NOT LOGGED');
            // Do something if not logged, like redirect to /login
            return context.redirect('/login');
        }
        resolve(user);
    }));
}

I made a proposition with $axios but of course you can change it.我用 $axios 提出了一个建议,但你当然可以改变它。 You just need to keep the middleware and the promise to have an asynchronous middleware.您只需要保留中间件并承诺有一个异步中间件。

Then on your page waiting for the query, you can add:然后在您等待查询的页面上,您可以添加:

export default {
    middleware: [
        'userLogged',
    ],
    data() {...}
};

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

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