diff --git a/site/content/docs/01-getting-started.md b/site/content/docs/01-getting-started.md deleted file mode 100644 index 753f571ebb..0000000000 --- a/site/content/docs/01-getting-started.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Getting started ---- - ---- - -To try Svelte in an interactive online environment you can try [the REPL](https://svelte.dev/repl) or [StackBlitz](https://node.new/svelte). - -To create a project locally we recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team: - -``` -npm create svelte@latest myapp -cd myapp -npm install -npm run dev -``` - -SvelteKit will handle calling [the Svelte compiler](https://www.npmjs.com/package/svelte) to convert your `.svelte` files into `.js` files that create the DOM and `.css` files that style it. It also provides all the other pieces you need to build a web application such as a development server, routing, and deployment. [SvelteKit](https://kit.svelte.dev/) utilizes [Vite](https://vitejs.dev/) to build your code and handle server-side rendering (SSR). There are [plugins for all the major web bundlers](https://sveltesociety.dev/tools#bundling) to handle Svelte compilation, which will output `.js` and `.css` that you can insert into your HTML, but most others won't handle SSR. - -If you don't need a full-fledged app framework and instead want to build a simple frontend-only site/app, you can also use Svelte (without Kit) with Vite by running `npm init vite` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS and CSS files inside the `dist` directory. - -The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) and there are integrations with various other [editors](https://sveltesociety.dev/tools#editor-support) and tools as well. - -If you're having trouble, get help on [Discord](https://svelte.dev/chat) or [StackOverflow](https://stackoverflow.com/questions/tagged/svelte). diff --git a/site/content/docs/00-introduction.md b/site/content/docs/01-getting-started/01-introduction.md similarity index 95% rename from site/content/docs/00-introduction.md rename to site/content/docs/01-getting-started/01-introduction.md index 11f82117e9..ea224ac791 100644 --- a/site/content/docs/00-introduction.md +++ b/site/content/docs/01-getting-started/01-introduction.md @@ -1,5 +1,5 @@ --- -title: Before we begin +title: Introduction --- This page contains detailed API reference documentation. It's intended to be a resource for people who already have some familiarity with Svelte. diff --git a/site/content/docs/01-getting-started/02-installation.md b/site/content/docs/01-getting-started/02-installation.md new file mode 100644 index 0000000000..baf91f3e02 --- /dev/null +++ b/site/content/docs/01-getting-started/02-installation.md @@ -0,0 +1,5 @@ +--- +title: Installation +--- + +TODO diff --git a/site/content/docs/01-getting-started/03-migrating-v3-to-v4.md b/site/content/docs/01-getting-started/03-migrating-v3-to-v4.md new file mode 100644 index 0000000000..21eca4d0d3 --- /dev/null +++ b/site/content/docs/01-getting-started/03-migrating-v3-to-v4.md @@ -0,0 +1,5 @@ +--- +title: Migrating from v3 to v4 +--- + +TODO diff --git a/site/content/docs/01-getting-started/meta.json b/site/content/docs/01-getting-started/meta.json new file mode 100644 index 0000000000..345e69a3c2 --- /dev/null +++ b/site/content/docs/01-getting-started/meta.json @@ -0,0 +1,3 @@ +{ + "title": "Getting Started" +} diff --git a/site/content/docs/02-component-format.md b/site/content/docs/02-basics/01-component-format.md similarity index 94% rename from site/content/docs/02-component-format.md rename to site/content/docs/02-basics/01-component-format.md index 90fbc3cd30..7e678495ff 100644 --- a/site/content/docs/02-component-format.md +++ b/site/content/docs/02-basics/01-component-format.md @@ -2,13 +2,11 @@ title: Component format --- ---- - Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. All three sections — script, styles and markup — are optional. -```sv +```svelte @@ -20,17 +18,15 @@ All three sections — script, styles and markup — are optional. ``` -### <script> +## <script> A ` ``` ---- - You can specify a default initial value for a prop. It will be used if the component's consumer doesn't specify the prop on the component (or if its initial value is `undefined`) when instantiating the component. Note that whenever a prop is removed by the consumer, its value is set to `undefined` rather than the initial value. In development mode (see the [compiler options](/docs/compile-time#svelte-compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`. -```sv +```svelte ``` ---- - If you export a `const`, `class` or `function`, it is readonly from outside the component. Functions are valid prop values, however, as shown below. -```sv +```svelte ``` Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs/template-syntax#component-directives-bind-this). ---- - You can use reserved words as prop names. -```sv +```svelte ``` -#### 2. Assignments are 'reactive' - ---- +### 2. Assignments are 'reactive' To change component state and trigger a re-render, just assign to a locally declared variable. Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect. -```sv +```svelte ``` ---- - Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. A subsequent assignment is required to trigger the update. This and more details can also be found in the [tutorial](/tutorial/updating-arrays-and-objects). -```sv +```svelte ``` ---- - Svelte's ` ``` -#### 3. `$:` marks a statement as reactive +### 3. `$:` marks a statement as reactive --- Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` [JS label syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed. -```sv +```svelte ``` ---- - Only values which directly appear within the `$:` block will become dependencies of the reactive statement. For example, in the code below `total` will only update when `x` changes, but not `y`. -```sv +```svelte Total: {total} - + - + ``` ---- - It is important to note that the reactive blocks are ordered via simple static analysis at compile time, and all the compiler looks at are the variables that are assigned to and used within the block itself, not in any functions called by them. This means that `yDependent` will not be updated when `x` is updated in the following example: -```sv +```svelte ``` -#### 4. Prefix stores with `$` to access their values - ---- +### 4. Prefix stores with `$` to access their values A _store_ is an object that allows reactive access to a value via a simple _store contract_. The [`svelte/store` module](/docs/run-time#svelte-store) contains minimal store implementations which fulfil this contract. @@ -241,7 +213,7 @@ Note that the store must be declared at the top level of the component — not i Local variables (that do not represent store values) must _not_ have a `$` prefix. -```sv +```svelte ``` -##### Store contract +#### Store contract ```js store = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void } @@ -270,9 +242,7 @@ You can create your own stores without relying on [`svelte/store`](/docs/run-tim For interoperability with RxJS Observables, the `.subscribe` method is also allowed to return an object with an `.unsubscribe` method, rather than return the unsubscription function directly. Note however that unless `.subscribe` synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as `undefined` until it does. -### <script context="module"> - ---- +## <script context="module"> A ` ``` -### <style> - ---- +## <style> CSS inside a ` ``` ---- - To apply styles to a selector globally, use the `:global(...)` modifier. -```sv +```svelte ``` ---- - If you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with `-global-`. The `-global-` part will be removed when compiled, and the keyframe then be referenced using just `my-animation-name` elsewhere in your code. @@ -359,8 +323,6 @@ The `-global-` part will be removed when compiled, and the keyframe then be refe ``` ---- - There should only be 1 top-level ` -``` - ---- - -So you can set a high-level theme color: - -```css -/* global.css */ -html { - --theme-color: black; -} -``` - ---- - -Or override it at the consumer level: - -```sv - -``` - -#### bind:_property_ - -```sv -bind:property={variable} -``` - ---- - -You can bind to component props using the same syntax as for elements. - -```sv - -``` - -#### bind:this - -```sv -bind:this={component_instance} -``` - ---- - -Components also support `bind:this`, allowing you to interact with component instances programmatically. - -> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error. - -```sv - - - -``` - -### `` - -```sv - -``` - -```sv - -``` - -```sv - -``` - ---- - -Components can have child content, in the same way that elements can. - -The content is exposed in the child component using the `` element, which can contain fallback content that is rendered if no children are provided. - -```sv - -
- - this fallback content will be rendered when no content is provided, like in the first example - -
- - - - - -

this is some child content that will overwrite the default slot content

-
-``` - -Note: If you want to render regular `` element, You can use ``. - -Note: If you want to render regular `` element, You can use ``. - -#### `` - ---- - -Named slots allow consumers to target specific areas. They can also have fallback content. - -```sv - -
- No header was provided -

Some content between header and footer

- -
- - - -

Hello

-

Copyright (c) 2019 Svelte Industries

-
-``` - -Components can be placed in a named slot using the syntax ``. -In order to place content in a slot without using a wrapper element, you can use the special element ``. - -```sv - -
- No header was provided -

Some content between header and footer

- -
- - - - - -

All rights reserved.

-

Copyright (c) 2019 Svelte Industries

-
-
-``` - -#### `$$slots` - ---- - -`$$slots` is an object whose keys are the names of the slots passed into the component by the parent. If the parent does not pass in a slot with a particular name, that name will not be present in `$$slots`. This allows components to render a slot (and other elements, like wrappers for styling) only if the parent provides it. - -Note that explicitly passing in an empty named slot will add that slot's name to `$$slots`. For example, if a parent passes `
` to a child component, `$$slots.title` will be truthy within the child. - -```sv - -
- - {#if $$slots.description} - -
- - {/if} -
- - - -

Blog Post Title

- -
-``` - -#### `` - ---- - -Slots can be rendered zero or more times and can pass values _back_ to the parent using props. The parent exposes the values to the slot template using the `let:` directive. - -The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `` is equivalent to ``. - -```sv - -
    - {#each items as item} -
  • - -
  • - {/each} -
- - - -
{thing.text}
-
-``` - ---- - -Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute. - -```sv - -
    - {#each items as item} -
  • - -
  • - {/each} -
- - - - - -
{item.text}
-

Copyright (c) 2019 Svelte Industries

-
-``` - -### `` - ---- - -The `` element allows a component to include itself, recursively. - -It cannot appear at the top level of your markup; it must be inside an if or each block or passed to a component's slot to prevent an infinite loop. - -```sv - - -{#if count > 0} -

counting down... {count}

- -{:else} -

lift-off!

-{/if} -``` - -### `` - -```sv - -``` - ---- - -The `` element renders a component dynamically, using the component constructor specified as the `this` property. When the property changes, the component is destroyed and recreated. - -If `this` is falsy, no component is rendered. - -```sv - -``` - -### `` - -```sv - -``` - ---- - -The `` element lets you render an element of a dynamically specified type. This is useful for example when displaying rich text content from a CMS. Any properties and event listeners present will be applied to the element. - -The only supported binding is `bind:this`, since the element type-specific bindings that Svelte does at build time (e.g. `bind:value` for input elements) do not work with a dynamic tag type. - -If `this` has a nullish value, the element and its children will not be rendered. - -If `this` is the name of a [void element](https://developer.mozilla.org/en-US/docs/Glossary/Void_element) (e.g., `br`) and `` has child elements, a runtime error will be thrown in development mode. - -```sv - - -Foo -``` - -### `` - -```sv - -``` - -```sv - -``` - ---- - -The `` element allows you to add event listeners to the `window` object without worrying about removing them when the component is destroyed, or checking for the existence of `window` when server-side rendering. - -Unlike ``, this element may only appear at the top level of your component and must never be inside a block or element. - -```sv - - - -``` - ---- - -You can also bind to the following properties: - -- `innerWidth` -- `innerHeight` -- `outerWidth` -- `outerHeight` -- `scrollX` -- `scrollY` -- `online` — an alias for `window.navigator.onLine` - -All except `scrollX` and `scrollY` are readonly. - -```sv - -``` - -> Note that the page will not be scrolled to the initial value to avoid accessibility issues. Only subsequent changes to the bound variable of `scrollX` and `scrollY` will cause scrolling. However, if the scrolling behaviour is desired, call `scrollTo()` in `onMount()`. - -### `` - -```sv - -``` - ---- - -Similarly to ``, this element allows you to add listeners to events on `document`, such as `visibilitychange`, which don't fire on `window`. It also lets you use [actions](/docs/template-syntax#element-directives-use-action) on `document`. - -As with ``, this element may only appear the top level of your component and must never be inside a block or element. - -```sv - -``` - -### `` - -```sv - -``` - ---- - -Similarly to ``, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave`, which don't fire on `window`. It also lets you use [actions](/docs/template-syntax#element-directives-use-action) on the `` element. - -As with `` and ``, this element may only appear the top level of your component and must never be inside a block or element. - -```sv - -``` - -### `` - -```sv -... -``` - ---- - -This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `html` content. - -As with ``, `` and ``, this element may only appear at the top level of your component and must never be inside a block or element. - -```sv - - - -``` - -### `` - -```sv - -``` - ---- - -The `` element provides a place to specify per-component compiler options, which are detailed in the [compiler section](/docs/compile-time#svelte-compile). The possible options are: - -- `immutable={true}` — you never use mutable data, so the compiler can do simple referential equality checks to determine if values have changed -- `immutable={false}` — the default. Svelte will be more conservative about whether or not mutable objects have changed -- `accessors={true}` — adds getters and setters for the component's props -- `accessors={false}` — the default -- `namespace="..."` — the namespace where this component will be used, most commonly "svg"; use the "foreign" namespace to opt out of case-insensitive attribute names and HTML-specific warnings -- `tag="..."` — the name to use when compiling this component as a custom element - -```sv - -``` - -### `` - -The `` element allows you to place content in a [named slot](/docs/template-syntax#slot-slot-name-name) without wrapping it in a container DOM element. This keeps the flow layout of your document intact. - -```sv - -
- No header was provided -

Some content between header and footer

- -
- - - -

Hello

- -

All rights reserved.

-

Copyright (c) 2019 Svelte Industries

-
-
-``` diff --git a/site/content/docs/03-template-syntax/01-basics.md b/site/content/docs/03-template-syntax/01-basics.md new file mode 100644 index 0000000000..db5544f58e --- /dev/null +++ b/site/content/docs/03-template-syntax/01-basics.md @@ -0,0 +1,134 @@ +--- +title: Basics +--- + +## Tags + +A lowercase tag, like `
`, denotes a regular HTML element. A capitalised tag, such as `` or ``, indicates a _component_. + +```svelte + + +
+ +
+``` + +## Attributes and props + +By default, attributes work exactly like their HTML counterparts. + +```svelte +
+ +
+``` + +As in HTML, values may be unquoted. + +```svelte + +``` + +Attribute values can contain JavaScript expressions. + +```svelte +page {p} +``` + +Or they can _be_ JavaScript expressions. + +```svelte + +``` + +Boolean attributes are included on the element if their value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and excluded if it's [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). + +All other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`). + +```svelte + +
This div has no title attribute
+``` + +An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed: + +```svelte + +``` + +When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. + +```svelte + + + +``` + +By convention, values passed to components are referred to as _properties_ or _props_ rather than _attributes_, which are a feature of the DOM. + +As with elements, `name={name}` can be replaced with the `{name}` shorthand. + +```svelte + +``` + +_Spread attributes_ allow many attributes or properties to be passed to an element or component at once. + +An element or component can have multiple spread attributes, interspersed with regular ones. + +```svelte + +``` + +_`$$props`_ references all props that are passed to a component, including ones that are not declared with `export`. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases – for example, when you don't know at compile time what props might be passed to a component. + +```svelte + +``` + +_`$$restProps`_ contains only the props which are _not_ declared with `export`. It can be used to pass down other unknown attributes to an element in a component. It shares the same optimisation problems as _`$$props`_, and is likewise not recommended. + +```svelte + +``` + +> The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable. + +> Sometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, ``, Svelte will attempt to set the value to `1` (rounding up from 0.5 as the step by default is 1), and then set the step to `0.1`. To fix this, change it to ``. + +> Another example is ``. Svelte will set the img `src` before making the img element `loading="lazy"`, which is probably too late. Change this to `` to make the image lazily loaded. + +## Text expressions + +```svelte +{expression} +``` + +Text can also contain JavaScript expressions: + +> If you're using a regular expression (`RegExp`) [literal notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#literal_notation_and_constructor), you'll need to wrap it in parentheses. + +```svelte +

Hello {name}!

+

{a} + {b} = {a + b}.

+ +
{/^[A-Za-z ]+$/.test(value) ? x : y}
+``` + +## Comments + +You can use HTML comments inside components. + +```svelte +

Hello world

+``` + +Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually, these are accessibility warnings; make sure that you're disabling them for a good reason. + +```svelte + + +``` diff --git a/site/content/docs/03-template-syntax/02-logic-blocks.md b/site/content/docs/03-template-syntax/02-logic-blocks.md new file mode 100644 index 0000000000..b0d6bcc471 --- /dev/null +++ b/site/content/docs/03-template-syntax/02-logic-blocks.md @@ -0,0 +1,206 @@ +--- +title: Logic Blocks +--- + +## {#if ...} + +```svelte +{#if expression}...{/if} +``` + +```svelte +{#if expression}...{:else if expression}...{/if} +``` + +```svelte +{#if expression}...{:else}...{/if} +``` + +Content that is conditionally rendered can be wrapped in an if block. + +```svelte +{#if answer === 42} +

what was the question?

+{/if} +``` + +Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause. + +```svelte +{#if porridge.temperature > 100} +

too hot!

+{:else if 80 > porridge.temperature} +

too cold!

+{:else} +

just right!

+{/if} +``` + +(Blocks don't have to wrap elements, they can also wrap text within elements!) + +## {#each ...} + +```svelte +{#each expression as name}...{/each} +``` + +```svelte +{#each expression as name, index}...{/each} +``` + +```svelte +{#each expression as name (key)}...{/each} +``` + +```svelte +{#each expression as name, index (key)}...{/each} +``` + +```svelte +{#each expression as name}...{:else}...{/each} +``` + +Iterating over lists of values can be done with an each block. + +```svelte +

Shopping list

+
    + {#each items as item} +
  • {item.name} x {item.qty}
  • + {/each} +
+``` + +You can use each blocks to iterate over any array or array-like value — that is, any object with a `length` property. + +An each block can also specify an _index_, equivalent to the second argument in an `array.map(...)` callback: + +```svelte +{#each items as item, i} +
  • {i + 1}: {item.name} x {item.qty}
  • +{/each} +``` + +If a _key_ expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change. + +```svelte +{#each items as item (item.id)} +
  • {item.name} x {item.qty}
  • +{/each} + + +{#each items as item, i (item.id)} +
  • {i + 1}: {item.name} x {item.qty}
  • +{/each} +``` + +You can freely use destructuring and rest patterns in each blocks. + +```svelte +{#each items as { id, name, qty }, i (id)} +
  • {i + 1}: {name} x {qty}
  • +{/each} + +{#each objects as { id, ...rest }} +
  • {id}
  • +{/each} + +{#each items as [id, ...rest]} +
  • {id}
  • +{/each} +``` + +An each block can also have an `{:else}` clause, which is rendered if the list is empty. + +```svelte +{#each todos as todo} +

    {todo.text}

    +{:else} +

    No tasks today!

    +{/each} +``` + +## {#await ...} + +```svelte +{#await expression}...{:then name}...{:catch name}...{/await} +``` + +```svelte +{#await expression}...{:then name}...{/await} +``` + +```svelte +{#await expression then name}...{/await} +``` + +```svelte +{#await expression catch name}...{/await} +``` + +Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected. In SSR mode, only the pending state will be rendered on the server. + +```svelte +{#await promise} + +

    waiting for the promise to resolve...

    +{:then value} + +

    The value is {value}

    +{:catch error} + +

    Something went wrong: {error.message}

    +{/await} +``` + +The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible). + +```svelte +{#await promise} + +

    waiting for the promise to resolve...

    +{:then value} + +

    The value is {value}

    +{/await} +``` + +If you don't care about the pending state, you can also omit the initial block. + +```svelte +{#await promise then value} +

    The value is {value}

    +{/await} +``` + +Similarly, if you only want to show the error state, you can omit the `then` block. + +```svelte +{#await promise catch error} +

    The error is {error}

    +{/await} +``` + +## {#key ...} + +```svelte +{#key expression}...{/key} +``` + +Key blocks destroy and recreate their contents when the value of an expression changes. + +This is useful if you want an element to play its transition whenever a value changes. + +```svelte +{#key value} +
    {value}
    +{/key} +``` + +When used around components, this will cause them to be reinstantiated and reinitialised. + +```svelte +{#key value} + +{/key} +``` diff --git a/site/content/docs/03-template-syntax/03-special-tags.md b/site/content/docs/03-template-syntax/03-special-tags.md new file mode 100644 index 0000000000..e4e677b6d6 --- /dev/null +++ b/site/content/docs/03-template-syntax/03-special-tags.md @@ -0,0 +1,84 @@ +--- +title: Special Tags +--- + +## {@html ...} + +```svelte +{@html expression} +``` + +In a text expression, characters like `<` and `>` are escaped; however, with HTML expressions, they're not. + +The expression should be valid standalone HTML — `{@html "
    "}content{@html "
    "}` will _not_ work, because `
    ` is not valid HTML. It also will _not_ compile Svelte code. + +> Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability. + +```svelte +
    +

    {post.title}

    + {@html post.content} +
    +``` + +## {@debug ...} + +```svelte +{@debug} +``` + +```svelte +{@debug var1, var2, ..., varN} +``` + +The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open. + +```svelte + + +{@debug user} + +

    Hello {user.firstname}!

    +``` + +`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions). + +```svelte + +{@debug user} +{@debug user1, user2, user3} + + +{@debug user.firstname} +{@debug myArray[0]} +{@debug !isReady} +{@debug typeof user === 'object'} +``` + +The `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when _any_ state changes, as opposed to the specified variables. + +## {@const ...} + +```svelte +{@const assignment} +``` + +The `{@const ...}` tag defines a local constant. + +```svelte + + +{#each boxes as box} + {@const area = box.width * box.height} + {box.width} * {box.height} = {area} +{/each} +``` + +`{@const}` is only allowed as direct child of `{#if}`, `{:else if}`, `{:else}`, `{#each}`, `{:then}`, `{:catch}`, `` or ``. diff --git a/site/content/docs/03-template-syntax/04-element-directives.md b/site/content/docs/03-template-syntax/04-element-directives.md new file mode 100644 index 0000000000..9b1b1b3841 --- /dev/null +++ b/site/content/docs/03-template-syntax/04-element-directives.md @@ -0,0 +1,763 @@ +--- +title: Element Directives +--- + +As well as attributes, elements can have _directives_, which control the element's behaviour in some way. + +## on:_eventname_ + +```svelte +on:eventname={handler} +``` + +```svelte +on:eventname|modifiers={handler} +``` + +Use the `on:` directive to listen to DOM events. + +```svelte + + + +``` + +Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters. + +```svelte + +``` + +Add _modifiers_ to DOM events with the `|` character. + +```svelte +
    + +
    +``` + +The following modifiers are available: + +- `preventDefault` — calls `event.preventDefault()` before running the handler +- `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element +- `stopImmediatePropagation` - calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired. +- `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so) +- `nonpassive` — explicitly set `passive: false` +- `capture` — fires the handler during the _capture_ phase instead of the _bubbling_ phase +- `once` — remove the handler after the first time it runs +- `self` — only trigger handler if `event.target` is the element itself +- `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action. + +Modifiers can be chained together, e.g. `on:click|once|capture={...}`. + +If the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it. + +```svelte + +``` + +It's possible to have multiple event listeners for the same event: + +```svelte + + + +``` + +## bind:_property_ + +```svelte +bind:property={variable} +``` + +Data ordinarily flows down, from parent to child. The `bind:` directive allows data to flow the other way, from child to parent. Most bindings are specific to particular elements. + +The simplest bindings reflect the value of a property, such as `input.value`. + +```svelte + +