我有一个<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>
Run Code Online (Sandbox Code Playgroud)
那么如何在表单提交时正确重定向用户?
查看工兵转到功能。它可以满足您的目的。
以下是如何使用您的代码。
<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>
Run Code Online (Sandbox Code Playgroud)