【发布时间】:2022-01-13 04:27:54
【问题描述】:
似乎所有的解决方案都需要 ssr(我们没有使用)。我使用的是adapter-static,用户存储在localStorage,所以SSR无论如何都不起作用。
我正在尝试保护需要在 svelte-kit 中登录的页面:
<script context="module">
import { authGuard } from '@lib/guard.js';
export async function load({ page, fetch, session, context }) {
return await authGuard({ page, fetch, session, context });
}
</script>
<script>
import { page } from '$app/stores';
import NavBar from '../components/NavBar.svelte';
import TopNav from '../components/TopNav.svelte';
let currentPage;
page.subscribe((path) => (currentPage = path));
</script>
{#if currentPage.path === '/login'}
<main class="sans-navbar">
<TopNav />
<section>
<slot />
</section>
</main>
{:else}
<main>
<NavBar />
<section>
<slot />
</section>
</main>
{/if}
<style>
main {
display: flex;
justify-content: flex-start;
min-height: 100vh;
}
main.sans-navbar {
flex-direction: column;
}
section {
padding: 2.4rem;
width: 100%;
min-height: 100vh;
background-color: #f2f6fa;
}
</style>
这是guard.js 库:
import { LoggedIn } from '../stores/user';
export async function authGuard({ page }) {
console.log(LoggedIn, page);
if (LoggedIn && page.path === '/login') {
return { status: 302, redirect: '/' };
} else if (LoggedIn) {
return {};
} else {
return { status: 302, redirect: '/login' };
}
}
export default {
authGuard
};
问题是LoggedIn需要localStorage,所以SSR解决方案不起作用。
【问题讨论】:
-
顺便说一句,您应该为商店使用
$,以便为您处理退订。而不是将page的值存储到currentPage,只需使用$page。