如何将<form>
元素定义为导出,然后您可以在其父级中使用它并定义onsubmit
事件监听器?您可以export let form;
在bind:this={form}
.<form>
在 Form.svelte 中:
<script>
export let form;
function validate() {
console.log("I'm the validate() function")
}
</script>
<form bind:this={form} on:submit|preventDefault={validate}>
<input>
<button type="submit">
Please save me
</button>
</form>
在 App.svelte 中:
<script>
import Form from "./Form.svelte"
import {onMount} from "svelte"
let form;
onMount(()=> {
form.onsubmit = handleOnSubmit
})
function handleOnSubmit() {
console.log("I'm the handleOnSubmit() in App.svelte")
}
</script>
<Form bind:form={form} on:submit={handleOnSubmit}>
</Form>