簡體   English   中英

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

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

使$auth.loggedIn可用的/api/user/請求發生在客戶端已經加載/開始加載之后。 這使得我的一些模塊在$auth.loggedIn變為 true/false 后呈現然后消失,使頁面加載時一切看起來都很混亂。

如果對/api/user/的調用以與 asyncData 請求相同的方式發生,以便$auth.loggedIn在任何呈現之前可用,那將是理想的。 是否有任何設置/配置使這成為可能? 我正在使用通用模式。

您可以在此處使用 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);
    }));
}

我用 $axios 提出了一個建議,但你當然可以改變它。 您只需要保留中間件並承諾有一個異步中間件。

然后在您等待查詢的頁面上,您可以添加:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM