svelte:Read-only bindings

offsetWidthoffsetHeightclientWidthclientHeight can be bound, read only, on any block level HTML element, excluding void tags (like br) and elements that are set to be inline (display: inline).

Get a reference to the HTML element in JavaScript

bind:this is a special kind of binding that allows you to get a reference to an HTML element and bind it to a JavaScript variable:

<script>
let myInputField
</script>

<input bind:this={myInputField} />

This is handy when you need to apply logic to elements after you mount them, for example, using the onMount() lifecycle event callback.

Binding components props

Using bind: you can bind a value to any prop that a component exposes.

Say you have a Car.svelte component:

<script>
export let inMovement = false
</script>

<button on:click={() => inMovement = true }>Start car</button>

You can import the component and bind the inMovement prop:

<script>
  import Car from './Car.svelte';

  let carInMovement;
</script>

<Car bind:inMovement={carInMovement} />

{carInMovement}

This can allow for interesting scenarios.

Leave a comment

Your email address will not be published. Required fields are marked *