[svelte] 배경 지식

sunclock·2021년 10월 7일
0

프론트엔드

목록 보기
3/8

Svelte 주의사항

보안

  • {@html ...} Svelte doesn't perform any sanitization of the expression inside {@html ...} before it gets inserted into the DOM. In other words, if you use this feature it's critical that you manually escape HTML that comes from sources you don't trust, otherwise you risk exposing your users to XSS attacks.

성능

  • There's no race condition in Svelte. only the recent promise is considered.
  • Inline event handlers in Svelte doesn't compromise performance.

데이터 흐름

  • Use component bindings sparingly. It can be difficult to track the flow of data around your application if you have too many of them, especially if there is no 'single source of truth'.

Svelte 기본 문법

State

  • reactive value
    • $: variable에 값이 할당되는 순간에 trigger
    • 참조한 값 update → render
    • array method 이용 불가. redundant declaration으로 trigger 해줘야.
    • the name of the updated variable must appear on the left hand side of the assignment.
  • props
    • 기존의 React에서 Component 단위로 export 하던 것과 다르게, 변수 단위로 export가 일어난다.
    • 자식 컴포넌트가 변수를 export 하면, 부모 컴포넌트 자식 컴포넌트의 props로 export된 변수에 값을 할당한다.
    • pass down object of props using spread syntax like <Info {...pkg}/>
    • (not recommended, but sometimes useful tips) $$props. export되지 않은 props에 직접 접근

Logic

  • 조건
    • {#if condition} {:else} {:else if condition} {/if}
  • 반복
    • 자료형
      • array-like object: {#each cats as { id, name }, index}
      • generic iterables: {#each [...iterable], index}
    • 선언
      • deconstruction:{#each cats as { id, name }, index}
      • keying:{#each things as thing ([thing.id](http://thing.id/))}
  • 비동기
    • {#await promise} {:then variable} {:catch error} {/await}
    • in short:{#await promise then value}{/await}

Event

  • DOM event handlers
    • <htmlTag on:event={handleEvent}> </htmlTag>
    • inline: <div on:mousemove="{e => m = { x: e.clientX, y: e.clientY }}">
    • DOM event handlers can have modifiers. Chaining modifiers together is also supported.
    • The full list of modifiers:
      • preventDefault — calls event.preventDefault() before running the handler. Useful for client-side form handling, for example.
      • stopPropagation — calls event.stopPropagation(), preventing the event reaching the next element
      • 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 (MDN docs)
      • 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.
  • Component event handlers
    • Components can dispatch events. example
    • Event forwarding is needed when listening to an event on some deeply nested components.
      • forward all message events: <InnerComponent on:message />
      • applies to DOM events too: <htmlTag on:click></htmlTag>

Data binding

  • <input bind:value={name}> not only will changes to the value of name update the input value, but changes to the input value will update name.
  • in short:<textarea bind:value></textarea>
  • 바인딩을 사용하면 안 좋은 경우: If you prefer to work with immutable data, you should avoid these bindings and use event handlers instead.
  • component binding is also supported. <Keypad bind:value={pin} on:submit={handleSubmit}/>

Lifecycle

  • Every component has a lifecycle that starts when it is created, and ends when it is destroyed.
  • It's recommended to put the fetch in onMount rather than at the top level of the , lifecycle functions don't run during SSR, which means we can avoid fetching data that should be loaded lazily once the component has been mounted in the DOM.
    import { onMount } from 'svelte';
    	
    let photos = [];
    	
    onMount(async() => {
    	const res = await fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`);
    	photos = await res.json();
    });
  • onDestroy() 메모리 누수 방지
  • The beforeUpdate function schedules work to happen immediately before the DOM is updated. afterUpdate is its counterpart, used for running code once the DOM is in sync with your data.
    • Note that beforeUpdate will first run before the component has mounted, so we need to check for the existence of div before reading its properties.
  • The tick function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).

Store

  • Auto subscription: unsubscription 자동화
    • Auto-subscription only works with store variables that are declared (or imported) at the top-level scope of a component.$variable
  • writable store, which means it has set and update methods in addition to subscribe.
  • readable(initialValue, function start(set) { return function stop() {});
    • The start function is called when the store gets its first subscriber; stop is called when the last subscriber unsubscribes.
  • derived(baseValue, derivedValue)
    • It's possible to derive a store from multiple inputs, and to explicitly set a value instead of returning it (which is useful for deriving values asynchronously). Consult the API reference for more information.
  • custom stores
    import { writable } from 'svelte/store';
    
    function createCount() {
    	const { subscribe, set, update } = writable(0);
    
    	return {
    		subscribe,
    		increment: () => update(n => n + 1),
    		decrement: () => update(n => n - 1),
    		reset: () => set(0)
    	};
    }
    
    export const count = createCount();
  • store bindings: $name += '!' assignment is equivalent to name.set($name + '!')

Component Composition

  • named slots
  • checking for slot contents
  • slot props example

Context

  • Since context is not reactive, values that change over time should be represented as stores: const { these, are, stores } = getContext(...);
  • If a component calls setContext(key, context), then any child component can retrieve the context with const context = getContext(key).
  • setContext and getContext must be called during component initialisation. Calling it afterwards - for example inside onMount - will throw an error.
  • context keys: object literal means the keys are guaranteed not to conflict in any circumstance const key = {}; export { key };
  • Module Context: We can do that by declaring a <script context="module"> block. Code contained inside it will run once, when the module first evaluates, rather than when a component is instantiated. Place this at the top of

Special Elements

  • <svelte:self {...props}> allows a component to contain itself recursively.
  • Dynamic Component: <svelte:component this={selected.component}/> A component can change its category altogether with svelte:component. Instead of a sequence of if block
  • Just as you can add event listeners to any DOM element, you can add event listeners to the window object with <svelte:window>
  • binding window elements is supported.<svelte:window bind:scrollY={y}/>
    • The list of properties you can bind to is as follows:
      • innerWidth

      • innerHeight

      • outerWidth

      • outerHeight

      • scrollX

      • scrollY

      • online — an alias for window.navigator.onLine

        All except scrollX and scrollY are readonly.

  • <svelte:body on:mouseenter={handleMouseenter} on:mouseleave={handleMouseleave} />
  • <svelte:head><link rel="stylesheet" href="tutorial/dark-theme.css"></svelte:head>
    • In server-side rendering (SSR) mode, contents of svelte:head are returned separately from the rest of your HTML.
  • <svelte:options/> element allows you to specify compiler options.
    • The options that can be set here 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"

      • tag="..." — the name to use when compiling this component as a custom element

        Consult the API reference for more information on these options.

  • svelte:fragment element allows you to place content in a named slot without wrapping it in a container DOM element. This keeps the flow layout of your document intact.

Debugging

  • {@debug variable}
profile
안녕하세요.

0개의 댓글