LoginSignup
1
2

More than 3 years have passed since last update.

Svelteでwatchする

Last updated at Posted at 2019-07-27

Svelteで使える router ないかなーと思ってsvelte-spa-router のソースを見ていたら、結構参考になったのでメモ。

Svelteで変数をwatchする

Svelteの機能で、vuejs の computed にあたる$:記法があり、これは通常は vuejs 同様に

svelte

$:fifth = $hogeStore.length * 5
$:tenth = $hogeStore.fuga.length * 10

みたいな感じで使うのだが

svelte

let fifth = null;
let tenth = null;
$:{
  fifth = $hogeStore.length * 5
  tenth = $hogeStore.fuga.length * 10
}

こういう感じで hogeStore を watch 出来る、この例だとあんまり有難みがないが、下記みたいな感じで利用されていた。

svelte-spa-router

/* routersListは最初に定義されているpathとcomponent名のセット */
/* $loc.location(現在のURL)が変更された場合に、
 そのpathに該当するcomponentを探してセットしている */

$: {
    component = null
    let i = 0
    while (!component && i < routesList.length) {
        const match = routesList[i].match($loc.location)
        if (match) {
            /* componentが表示されるコンポーネント */
            component = routesList[i].component
            componentParams = match
        }
        i++
    }
}

Storeでイベントを監視する

Svelte の store で個人的に謎だったのが readable の存在で、どういう時に使うものなのか疑問だったのだが、こちらも svelte-spa-router で「監視しているイベントが発火したら store を更新する」という使い方をされていた。

svelte-spa-router

export const loc = readable(
    /* getLocationは現在のURLとQueryを返してくる */
    getLocation(),

    function start(set) {
        const update = () => {
            set(getLocation())
        }
        /* hashchangeイベントが発火したらupdateを実行してstoreを更新する */
        window.addEventListener('hashchange', update, false)

        return function stop() {
            window.removeEventListener('hashchange', update, false)
        }
    }
)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2