Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Svelte Valtio State Management

License

NotificationsYou must be signed in to change notification settings

hunghg255/sveltejs-valtio

Repository files navigation

State management solution for Svelte using proxies. Powered byvaltio.

Demo

Demo

Installation

npm i sveltejs-valtio

Usage

// store.tsimport{proxy}from'sveltejs-valtio';exportconststate=proxy({count:0});

Read from snapshots, mutate the source.

<scriptlang="ts">import {useSnapshot }from'sveltejs-valtio'import {state }from'./store'const snap=useSnapshot(state)</script><buttonon:click={()=>state.count++}>  Clicks: {$snap.count}</button>

Utilities

derive

You can subscribe to some proxies and create a derived proxy.

import{derive}from'sveltejs-valtio/utils';// create a base proxyconststate=proxy({count:1,});// create a derived proxyconstderived=derive({doubled:(get)=>get(state).count*2,});// alternatively, attach derived properties to an existing proxyderive({tripled:(get)=>get(state).count*3,},{proxy:state,},);

proxyWithComputed

You can define own computed properties within a proxy. By combining with a memoization library such asproxy-memoize, optimizing function calls is possible.

importmemoizefrom'proxy-memoize';import{proxyWithComputed}from'sveltejs-valtio/utils';conststate=proxyWithComputed({count:1,},{doubled:memoize((snap)=>snap.count*2),},);// Computed values accept custom setters too:conststate2=proxyWithComputed({firstName:'Alec',lastName:'Baldwin',},{fullName:{get:memoize((snap)=>`${snap.firstName}${snap.lastName}`),set:(state,newValue)=>{[state.firstName,state.lastName]=newValue.split(' ');},},},);// if you want a computed value to derive from another computed, you must declare the dependency first:conststate=proxyWithComputed({count:1,},{doubled:memoize((snap)=>snap.count*2),quadrupled:memoize((snap)=>snap.doubled*2),},);

proxyWithHistory

This is a utility function to create a proxy with snapshot history.

import{proxyWithHistory}from'sveltejs-valtio/utils';conststate=proxyWithHistory({count:0});console.log(state.value);// ---> { count: 0 }state.value.count+=1;console.log(state.value);// ---> { count: 1 }state.undo();console.log(state.value);// ---> { count: 0 }state.redo();console.log(state.value);// ---> { count: 1 }

[8]ページ先頭

©2009-2025 Movatter.jp