【发布时间】:2021-10-16 19:23:10
【问题描述】:
这里是 REPL:https://svelte.dev/repl/56770fec88af4b76bdc8ea962178854e?version=3.42.1
代码如下:
App.svelte:
<script>
import {editableStore} from "./store";
let name = "John"
$: player = editableStore(name);
</script>
<h1>Hello {$player.name}!</h1>
<button on:click={() => name = (name === "Bob" ? "Jerry" : "Bob")}>
Change name
</button>
<h2>Log:</h2>
{#each $player.log as log}
<li>{log}</li>
{/each}
store.js:
import {writable} from "svelte/store";
const defaultStore = {
name: "Bob",
age: 18,
log: []
};
export const editableStore = (name) => {
console.log("Recreated with name:", name);
const {subscribe, update} = writable({...defaultStore}, () => () => clearInterval);
if (name) {
update(s => ({...s, name}));
}
const clearInterval = setInterval(() => {
update(s => ({...s, log: [...s.log, new Date()]}))
}, 1000)
return { subscribe };
};
如您所见,如果您点击“更改名称”,商店就会重新创建。
这是我需要避免的。
但是怎么做呢?
【问题讨论】:
-
您应该遵循 Svelte 商店教程:svelte.dev/tutorial/writable-stores
标签: javascript svelte svelte-3 svelte-component svelte-store