0
0
mirror of https://github.com/sveltejs/svelte.git synced 2024-12-01 17:30:59 +01:00

Add tutorial for component binding (#5009)

Closes #5008

Co-authored-by: Stephane Vanraes <stephane.vanraes@fjordline.com>
Co-authored-by: pngwn <pnda007@gmail.com>
This commit is contained in:
Stephane 2021-06-26 20:09:49 +02:00 committed by GitHub
parent 92422fdee2
commit f9b796cabe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,5 @@
<script>
import InputField from './InputField.svelte';
</script>
<InputField />

View File

@ -0,0 +1,9 @@
<script>
let input;
export function focus() {
input.focus();
}
</script>
<input bind:this={input} />

View File

@ -0,0 +1,9 @@
<script>
import InputField from './InputField.svelte';
let field;
</script>
<InputField bind:this={field}/>
<button on:click={() => field.focus()}>Focus field</button>

View File

@ -0,0 +1,9 @@
<script>
let input;
export function focus() {
input.focus();
}
</script>
<input bind:this={input} />

View File

@ -0,0 +1,19 @@
---
title: Binding to component instances
---
Just as you can bind to DOM elements, you can bind to component instances themselves. For example, we can bind the instance of `<InputField>` to a prop named `field` in the same way we did when binding DOM Elements
```html
<InputField bind:this={field} />
```
Now we can programmatically interact with this component using `field`.
```html
<button on:click="{() => field.focus()}">
Focus field
</button>
```
> Note that we can't do `{field.focus}` since field is undefined when the button is first rendered and throws an error.