1.0.3 • Published 2 years ago
svelte-single-store-no1 v1.0.3
创建
import { SingleStore } from "svelte-single-store"
export const single = SingleStore({
state: {
count: 0,
NAME: {
sing: "Single",
K: {
name: "KL",
count: 0,
},
A: [1, 2, 3],
},
A: {
s: "SSSS",
},
AGE: 28,
loading: false,
},
setState: {
"[count|NAME-sing|NAME-A|NAME-K-name|A-s]": (data) => {
if (data.count === 2) {
return '等于2'
}else{
return '懒得打'
}
},
"[count]": (data) => {
return data.count
},
},
update: {
count: (oldVal: number) => oldVal + 1,
"NAME-sing": (oldVal: string) => "sing"+oldVal,
"NAME-A": (oldVal: any[]) => [...oldVal,5,6,7],
},
methods: {
async use(data) {
this.loading = true
await new Promise((res) => setTimeout(res, 8000))
this.loading = false
return data
},
},
})
使用
const { useStoreMethod, viewStore, updateStore } = single()
const count = viewStore("count")
const sing = viewStore("NAME-sing")
const A = viewStore("NAME-A")
const use = useStoreMethod('use','传参')
const partState = getState("[count|NAME-sing|NAME-A|NAME-K-name|A-s]")
const countState = getState("[count]")
$: console.log($partState)
$: console.log($countState)
<h1>{$count}</h1>
<h1>{$sing}</h1>
<h1>{$A}</h1>
<button
on:click={() => {
updateStore("count")
updateStore("NAME-sing")
updateStore("NAME-A")
}}>点击</button
>