gpt4 book ai didi

javascript - Svelte 商店功能更新

转载 作者:行者123 更新时间:2023-12-05 00:34:39 25 4
gpt4 key购买 nike

Svelte 商店文档显示 String 或 Integer 正在更新,但我没有在商店中找到任何动态函数。
我不明白如何制作 getData作为可写函数,以通知 html 更改。
在以下示例中,我想要 bupdateKey 之后显示函数被调用。
您将在此处找到 REPL 中的最小代码:https://svelte.dev/repl/3c86bd48d5b5428daee514765c926e58?version=3.29.7
如果 REPL 失败,这里的代码相同:
App.svelte:

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

<h1>{getData()}!</h1>
store.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';
}
目标是在商店中使用动态功能。

最佳答案

好吧,我认为您仍然对 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>
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])

关于javascript - Svelte 商店功能更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64862161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com