Svelte學習記錄2
接下來學的則是會跟其他檔案一起串接
串接子組件,要透過聲明屬性’props’,然後用export
的方式去串接
App.svelte
<script>
import Nested from './Nested.svelte';
</script>
<Nested answer={42} />
<Nested />
Nested.svelte
<script>
export let answer = 'a mystery';
</script>
<p>The answer is {answer}</p>
得出來的結果是:
The answer is 42
The answer is a mystery
然後記得一個是import 另一個是export,然後除了nested42 之外還需要一個nested的組件去接收原本的默認值:The answer is a mystery
- *查:PackageInfo,版本未定義
‘Logic’:因為html沒有辦法可以寫條件的內容,所以可以透過大括號{}
的方式去撰寫if & else & if else
,ex
{#if count > 10}
<p>{count} is greater than 10</p>
{:else if count < 5}
<p>{count} is less than 5</p>
{:else}
<p>{count} is between 5 and 10</p>
{/if}
然後#
是開始標記,:
繼續標記,/
是結束標記
>有很多button,但每一個顏色都不一樣,所以可以透過前面先定義好,之後就不用一個一個寫{#each colors as color, i},{/each}
<script>
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
let selected = colors[0];
</script>
<h1 style="color: {selected}">Pick a colour</h1>
<div>
{#each colors as color, i}
<button
aria-current={selected === color}
aria-label={color}
style="background: {color}"
on:click={() => selected = color}
>{i + 1}</button>
{/each}
</div>
<style>
h1 {
transition: color 0.2s;
}
div {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 5px;
max-width: 400px;
}
button {
aspect-ratio: 1;
border-radius: 50%;
background: var(--color, #fff);
transform: translate(-2px,-2px);
filter: drop-shadow(2px 2px 3px rgba(0,0,0,0.2));
transition: all 0.1s;
}
button[aria-current="true"] {
transform: none;
filter: none;
box-shadow: inset 3px 3px 4px rgba(0,0,0,0.2);
}
</style>
>Keyed each blocks,定義部分,用id去呼叫會比較安全,不會有重複命名然後呼叫錯誤的問題
・查await blocks
>Event Modifiers
preventDefault
— callsevent.preventDefault()
before running the handler. Useful for client-side form handling, for example.stopPropagation
— callsevent.stopPropagation()
, preventing the event reaching the next elementpassive
— improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)nonpassive
— explicitly setpassive: 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 runsself
— only trigger handler if event.target is the element itselftrusted
— only trigger handler ifevent.isTrusted
istrue
, meaning the event was triggered by a user action rather than because some JavaScript calledelement.dispatchEvent(...)
>Component events
組件也可以調度事件
・查:dom事件還有component事件監聽
>Event forwarding
<script>
import Inner from './Inner.svelte';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function forward(event) {
dispatch('message', event.detail);
}
</script>
<Inner on:message={forward}/>
用一行去代替他,這應該是Svelte自己內建的
<script>
import Inner from './Inner.svelte';
</script>
<Inner on:message />
一個沒有值的 on:message 事件指令表示“轉發所有消息事件”
・查on:message還可以替代什麼
>DOM event forwarding
跟上面那個方法是一樣的,所以要搞清楚event fording主要轉發的功能要怎麼運作
學習資源:Learn.svelte.dev