持久性斯维尔特5州
一个轻量级,类型安全的Svelte应用程序管理解决方案,具有内置存储持久性.
特征
- 🎯 类型安全: 带有自动类型推论的完整类型脚本支持
- 💾 持久性存储: 本地Storage 或会话中自动状态持续
- 🪶 轻巧: 斯韦尔特以外的零依赖性
- ⚡ 反应: 与斯维尔特反应系统的无缝集成
- 🔄 自动同步: 自动同步各个组件的状态
- 📦 简单 API: 只有一个功能来管理您的状态需求
安装
npm install @friendofsvelte/state
快速启动
- 使用
PersistentState数字 :
// new.svelte.ts / js
import { PersistentState } from '@friendofsvelte/state';
export const box = new PersistentState(
'box',
{
color: '#ff3e00',
dimensions: [100, 100]
},
'sessionStorage'
);
- 在组件中使用 :
<script lang="ts">
import { box } from '$lib/new.svelte';
const listColors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'brown'];
function switchNextColor() {
const currentIndex = listColors.indexOf(box.current.color);
const nextIndex = currentIndex + 1;
if (nextIndex >= listColors.length) {
box.current.color = listColors[0];
} else {
box.current.color = listColors[nextIndex];
}
}
</script>
<div
style="background-color: {box.current
.color}; width: 100px; height: 100px; color: gray; text-align: center;"
class="m-2 rounded-2xl"
>
{box.current.color}
</div>
<button onclick={switchNextColor} class="m-2 rounded-2xl bg-gray-700 px-3 text-gray-200">
Change color
</button>
API 参考
PersistentState<T>(key: string, initial?: T, storageType: StorageType = 'localStorage')
创建或检索持久性状态容器.
参数:
key: 国家容器的独特标识符initial: (可选) 初始状态值storageType: (可选) 存储类型 - “ localStorage” 或“ sessionStorage” (默认: “localStorage” )
回返情况:
- 类型反应状态对象
T
根据,富豪哈里斯' 本地存储测试
实例
基本用途
<script lang="ts">
import { PersistentState } from '@friendofsvelte/state';
const box = new PersistentState(
'box',
{
color: '#ff3e00',
dimensions: [100, 100]
},
'sessionStorage'
);
function switchNextColor() {
const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink', 'brown'];
const currentIndex = colors.indexOf(box.current.color);
box.current.color = colors[(currentIndex + 1) % colors.length];
}
</script>
<div
style="background-color: {box.current
.color}; width: 100px; height: 100px; color: gray; text-align: center;"
class="m-2 rounded-2xl"
>
{box.current.color}
</div>
<button onclick={switchNextColor} class="m-2 rounded-2xl bg-gray-700 px-3 text-gray-200">
Change color
</button>
捐款
欢迎捐款! 请随意提交 拉请求。 。 。 .
许可证
麻省理工学院许可证 - 详情见LICENSE文件