Svelte商店功能更新

Baa*_*art 4 javascript svelte svelte-store svelte-3

Svelte 存储文档显示正在更新字符串或整数,但我没有在存储中找到任何动态函数。

我不明白如何使该getData函数可写,以便通知 html 更改。

在下面的示例中,我希望在调用函数b后显示。updateKey

您可以在此处找到 REPL 中的最小代码:https://svelte.dev/repl/3c86bd48d5b5428daee514765c926e58 ?version=3.29.7

此处使用相同的代码,以防 REPL 宕机:

应用程序.svelte:

<script>
import { getData } from './store.js';
import { updateKey } from './store.js';
setTimeout(updateKey, 1000);
</script>

<h1>{getData()}!</h1>
Run Code Online (Sandbox Code Playgroud)

商店.js

import {setContext} from 'svelte';
import {writable} from 'svelte/store';

var data = {
    'a': 'a',
    'b': 'b'
};

var key = 'a';

export const getData = function() {
    return data[key];
}

export const updateKey = () => {
    key = 'b';
}
Run Code Online (Sandbox Code Playgroud)

目标是在商店中使用动态功能。

rix*_*ixo 12

好吧,我认为您对 Svelte 中的工作方式仍然有些困惑...不知道如何最好地回答您的问题,所以这里有一些您想要实现的目标的代码,以及一些注释。我希望它能帮助您更好地了解商店中的事物是如何组合在一起的。

App.svelte

<script>
    import { onMount } from 'svelte'
    import { key, data, updateKey } from './store.js'

    onMount(() => {
        // it's not safe to have an unchecked timer running -- problems would
        // occur if the component is destroyed before the timeout has ellapsed,
        // that's why we're using the `onMount` lifecycle function and its
        // cleanup function here
        const timeout = setTimeout(updateKey, 1000);
        
        // this cleanup function is called when the component is destroyed
        return () => {
            clearTimeout(timeout)
        }
    })

    // this will log the value of the `key` store each time it changes, using
    // a reactive expression (a Sveltism)
    $: console.log($key)
</script>

<!--
  NOTE: we're using the $ prefix notation to access _the value_ of the store,
        and not `data`, which would be _the store itself_ (an object with
        subscribe, set, etc.)
  -->
<h1>{$data}</h1>
Run Code Online (Sandbox Code Playgroud)

store.js

import { writable, derived } from 'svelte/store'

const db = {
    'a': 'a',
    'b': 'b'
}

// a writable store with initial value 'a'
export const key = writable('a')

export const updateKey = () => {
    // a writable store has a `set` method to change its value
    key.set('b')
}

// you can use a derived store to compute derived values from
// the current value of other stores
//
// here, we're getting the value from the db when the value of
// the `key` store changes
export const data = derived([key], ([$key]) => db[$key])
Run Code Online (Sandbox Code Playgroud)