提交表单后重定向用户

时间:2019-10-23 16:25:04

标签: svelte sapper

我在<input type="text" />中有一个<form>作为搜索栏。

由于是搜索栏,因此在提交表单时应将用户重定向到类似于/search?q=thingIWantToSearch的路由。

当前我正在使用location.href,但我认为这不是一种很好的方法(或者是吗?)

这是我的代码:

<script>
    let inputValue = '';

    const handleSubmit = () => {
        // there should be some parsing before putting it in the url, but it's not the subject
        location.href = `/search?q=${inputValue}`;
    }
</script>

<form on:submit|preventDefault={handleSubmit}>
    <input type="text" bind:value={inputValue} />
    <button type="submit">submit</button>
</form>

那么如何在提交表单时正确地重定向用户?

1 个答案:

答案 0 :(得分:3)

Check out Sappers goto function。它可以满足您的目的。

这是将代码与之配合使用的方式。

<script>
  import { goto } from '@sapper/app';

  let inputValue = '';

  const handleSubmit = () => {
    // there should be some parsing before putting it in the url, but it's not the subject
    goto(`/search?q=${inputValue}`);
  };
</script>

<form on:submit|preventDefault="{handleSubmit}">
  <input type="text" bind:value="{inputValue}" />
  <button type="submit">submit</button>
</form>