因为它是一个可写的商店,你可以打电话给
set
或
update
docs
).
例如:
import { writable } from 'svelte/store';
const apiURL = "https://jsonplaceholder.typicode.com/todos";
async function getData(){
const response = await fetch(apiURL);
const data = (await response.json()).slice(0,20);
testStore.set(data) // <================================
}
getData();
export const testStore = writable([])
然而,这个特定的用例似乎最好由一个
readable
商店。可读存储器将其初始值作为第一个参数,“生命周期”函数作为第二个参数。生命周期函数接收
设置
函数更改存储值,但存储本身不公开
或
更新
例如:
import { readable } from 'svelte/store';
const apiURL = "https://jsonplaceholder.typicode.com/todos";
const getData = async () => {
const res = await fetch(apiURL)
if (!res.ok) throw new Error('Bad response')
const items = await res.json()
return items.slice(0, 20)
}
export const todos = readable([], set => {
// called when the store is first subscribed (when subscribers goes from 0 to 1)
getData()
.then(set)
.catch(err => {
console.error('Failed to fetch', err)
})
return () => {
// you can do cleanup here if needed
}
})
最后,在
.svelte
$
直接获取它们的价值。使用这种表示法,Svelte将在需要时自动订阅存储,并在组件被销毁时取消订阅。
所以在你的例子中,使用
todos
存储在上面,您可以将组件更改为:
<script>
import { todos } from './store.js';
</script>
<h1>Todos:</h1>
{#each $todos as item}
<p>{item.title}</p>
{/each}