有時,您將需要多個不相關(guān)的組件或常規(guī)的JavaScript模塊訪問這些值锨天。
在Svelte囱淋,我們通過store來做到這一點。store只是一種對象,該對象具有一種subscribe方法纠亚,該方法允許在store的value發(fā)生變化時通知訂閱過的組件塘慕。
可寫 store
通過 writable 方法可以創(chuàng)建一個可寫store,傳入兩個參數(shù)value, start蒂胞。
- value:初始值
- start:獲得第一個訂閱者時調(diào)用图呢,擁有一個參數(shù)為set的回調(diào)∑妫可以返回一個stop方法蛤织,該方法在最后一個訂閱者退訂時執(zhí)行。
import { writable } from 'svelte/store';
export const count = writable(0,(set)=>{
console.log('subscribe count')
set(100)
return ()=>{
console.log('clear count')
}
});
可讀store擁有三個方法:update 鸿染、set指蚜、subscribe。
- set: 設(shè)置value值牡昆。
- update: 更新value值姚炕,接受一個參數(shù)為value的方法,return一個新的value值丢烘。
function update(fn) {
set(fn(value));
}
- subscribe: 訂閱該store,接受一個參數(shù)為value的方法些椒,用于獲得value值并進行處理播瞳。返回值為一個退訂方法,執(zhí)行該方法完成退訂免糕。
<script>
import { onDestroy } from "svelte";
import { count } from "../stores";
let count_value;
const unsubscribe = count.subscribe(value => {
count_value = value;
});
onDestroy(unsubscribe());
</script>
<h1>The count is {count_value}</h1>
<button
on:click={() => {
count.update(c => c - 1);
}}>
-
</button>
<button
on:click={() => {
count.update(c => c + 1);
}}>
+
</button>
<button
on:click={() => {
count.set(0);
}}>
reset
</button>
自動訂閱
使用$進行自動訂閱赢乓,自動訂閱的store將在組件銷毀時自動調(diào)用停止訂閱方法。
<script>
import { onDestroy } from "svelte";
import { count } from "../stores";
</script>
<h1>The count is {$count}</h1>
<button
on:click={() => {
count.update(c => c - 1);
}}>
-
</button>
<button
on:click={() => {
count.update(c => c + 1);
}}>
+
</button>
<button
on:click={() => {
count.set(0);
}}>
reset
</button>
只讀store
只讀store就是沒有暴露update石窑、set方法的可寫store牌芋。
import {
readable
} from 'svelte/store';
export const time = readable(new Date(), function start(set) {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return function stop() {
clearInterval(interval);
};
});
<script>
import { time } from '../stores';
const formatter = new Intl.DateTimeFormat('en', {
hour12: true,
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
});
</script>
<h1>The time is {formatter.format($time)}</h1>
派生store
您可以使用創(chuàng)建一個store,并且這個store基于其他一個或者多個store松逊,可以使用派生store躺屁。
export const elapsed = derived(
time,
$time => Math.round(($time - start) / 1000)
);
derived接受三個參數(shù):
- stores:可以為一個store對象,或者為一個數(shù)組经宏。
- fn:接受一個方法包含兩個參數(shù)values犀暑,set。如果stores為數(shù)組烁兰,values也為數(shù)組耐亏,如果stores為store對象,values為改store的value沪斟。如果沒有set參數(shù)广辰,派生store的value為fn的返回值,如果包含set參數(shù)可以使用set方法指定value值。
- initial_value:初始值(異步時使用)
綁定 store
如果store是可寫的(即它具有set方法)择吊,則可以綁定其值李根,就像可以綁定到本地組件一樣。
也可以通過直接賦值將value寫進store干发。
<input bind:value={$count}>
<button on:click="{() => $count += 1}">
+ 1
</button>
本教程的所有代碼均上傳到github有需要的同學(xué)可以參考 https://github.com/sullay/svelte-learn朱巨。