Svelte 中状态管理(store)的简单用法

正文

以简单计数器为例,计数变量放在 store-state 中,它使用 svelte/store 中的 writable 方法,它会返回一个对象,通过调用对象上的 .set(val) 进行重置、调用 .update((val) => ...) 进行更新、调用 .subscribe(val => ...) 进行订阅。

<script>
  // 创建仓库
  import { writable } from 'svelte/store'
  // 声明一个可写的 state 并指定初始值
  const count = writable(0)


  // 用于接收、订阅 count 值变动
  let countVal;

  // 订阅
  count.subscribe((val) => {
    // 订阅 store-state
    countVal = val;
  });

  // 增加
  const increment = () => {
    // 更新 store-state
    count.update((n) => n + 1);
  };
  // 减少
  const decrement = () => {
    // 更新 store-state
    count.update((n) => n - 1);
  };
  // 重置
  const reset = () => {
    // 重置 store-state
    count.set(0);
  };
</script>

<h1>{countVal}</h1>

<button on:click={increment}>+</button>
<button on:click={decrement}>-</button>
<button on:click={reset}>reset</button>

参考

https://www.sveltejs.cn/tutorial/writable-stores

原文地址:https://www.cnblogs.com/aisowe/p/15245574.html