Svelte 存储文档显示正在更新字符串或整数,但我没有在存储中找到任何动态函数。
我不明白如何制作getData
作为可写函数以通知 html 发生的变化。
在下面的示例中,我想b
后显示updateKey
函数被调用。
您将在此处找到 REPL 中的最小代码:https://svelte.dev/repl/3c86bd48d5b5428daee514765c926e58?version=3.29.7 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>
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])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)