Svelte state management
Skill morning-start/agent-skills/lang/svelte/svelte-state-management
AI 编程助手的专业技能库,涵盖 30+ 技能,按 6 类组织
npx -y skills add morning-start/agent-skills --skill svelte-state-managementAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
2 things to look at
- no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
- 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its author says it does
Copied from the file, not written here
Svelte 状态管理技能,掌握 Stores 和 Context API,实现跨组件状态共享和依赖注入
SKILL.md
2.5 KB, as published. Nobody here has run it
Svelte State Management
任务目标
- 本 Skill 用于:管理跨组件共享状态
- 能力包含:Store 创建与使用、Context 上下文、响应式状态导出
- 触发条件:需要在多个组件间共享状态时
操作步骤
使用 Stores
创建 Writable Store
import { writable } from 'svelte/store';
export const count = writable(0);
count.subscribe(value => console.log(value));
count.set(1);
count.update(n => n + 1);
创建 Readable Store
import { readable } from 'svelte/store';
const time = readable(new Date(), (set) => {
const interval = setInterval(() => set(new Date()), 1000);
return () => clearInterval(interval);
});
创建 Derived Store
import { derived } from 'svelte/store';
const doubled = derived(count, $count => $count * 2);
const summed = derived([a, b], ([$a, $b]) => $a + $b);
在组件中使用
<script>
import { count } from './stores';
</script>
<p>计数: {$count}</p>
<button onclick={() => $count++}>+1</button>
使用 Context
创建 Context
// context.js
import { createContext } from 'svelte';
export const [getUserContext, setUserContext] = createContext();
设置 Context
<!-- Parent.svelte -->
<script>
import { setUserContext } from './context';
setUserContext({ name: 'Alice' });
</script>
获取 Context
<!-- Child.svelte -->
<script>
import { getUserContext } from './context';
const user = getUserContext();
</script>
<p>你好, {user.name}</p>
使用 setContext/getContext
<script>
import { setContext, getContext } from 'svelte';
setContext('theme', 'dark');
const theme = getContext('theme');
</script>
响应式状态对象
// state.svelte.js
export const userState = $state({
name: 'John',
age: 30
});
<script>
import { userState } from './state.svelte.js';
</script>
<p>{userState.name}</p>
<button onclick={() => userState.age++}>长大</button>
资源索引
注意事项
- $ 前缀的 store 变量会在组件初始化时自动订阅
- Context 在组件树中是键值对存储
- createContext 提供更好的类型安全
- 避免在 SSR 时使用全局模块状态,使用 Context