乐闻世界logo
搜索文章和话题

How to route programmatically in SvelteKit?

1个答案

1

In SvelteKit, programmatic routing refers to controlling page navigation and redirection through code rather than via click-based links. This approach is highly beneficial when dynamically navigating based on specific logical conditions is required, such as automatically redirecting to different pages after a user completes a form.

How to Implement Programmatic Routing

SvelteKit provides a module named $app/navigation that includes functionality for implementing programmatic routing. Specifically, you can use the goto function to implement page navigation.

Here are the basic steps to use this functionality:

  1. Import the goto function:
    Within your Svelte component, you first need to import the goto function.

    javascript
    import { goto } from '$app/navigation';
  2. Use the goto function for navigation:
    You can invoke the goto function within any event handler or lifecycle function to change the route.

    javascript
    function handleSomeAction() { goto('/some-path'); }
  3. Pass parameters:
    If needed, the goto function can accept a second parameter to specify navigation behavior. For instance, you can set { replaceState: true } to replace the current entry in the history stack instead of adding a new one.

    javascript
    function handleSubmit() { goto('/success-page', { replaceState: true }); }

Suppose you have a login page where, after the user fills out the form and clicks the login button, you want to redirect to different pages based on the user's role. Here's how to implement this logic using programmatic routing:

svelte
<script> import { goto } from '$app/navigation'; let userInfo = { username: '', password: '' }; async function loginUser() { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userInfo) }); if (response.ok) { const userRole = await response.json(); if (userRole === 'admin') { goto('/admin-dashboard'); } else { goto('/user-dashboard'); } } else { console.error('Login failed'); } } </script> <form on:submit|preventDefault={loginUser}> <!-- Form Fields --> <button type="submit">Login</button> </form>

In this example, after the user fills out the form and submits it, the application invokes the loginUser function. This function first sends a login request to the server, then uses the goto function to navigate the user to the appropriate page based on the user's role as returned by the server. This approach efficiently handles dynamic navigation and is suitable for scenarios where routing decisions must be made based on logical conditions.

2024年8月16日 21:46 回复

你的答案