【问题标题】:How to have auth.loggedIn before rendering in Nuxt.js?在 Nuxt.js 中渲染之前如何拥有 auth.loggedIn?
【发布时间】:2021-03-07 21:00:06
【问题描述】:

使$auth.loggedIn 可用的/api/user/ 请求发生在客户端已经加载/开始加载之后。这使得我的一些模块在$auth.loggedIn 变为真/假后呈现然后消失,使得页面加载时一切看起来都很混乱。

如果对/api/user/ 的调用以与asyncData 请求相同的方式发生,那么$auth.loggedIn 在任何渲染之前都可用,那将是理想的。是否有任何设置/配置使这成为可能?我用的是通用模式。

【问题讨论】:

标签: javascript vue.js nuxt.js


【解决方案1】:

可以使用 Nuxt here 中定义的中间件 在您的情况下,您可以像这样在/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);
    }));
}

我用 $axios 提出了一个建议,但你当然可以改变它。您只需要保留中间件并承诺拥有异步中间件。

然后在你等待查询的页面上,可以添加:

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

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多