getContext和setContext函数只能在组件初始化期间调用。是否有某种方法可以在运行时(例如,单击事件)期间更新上下文值。 假设我们将主题或本地化存储在上下文值中,并希望创建一个按钮来更改它。有可能吗? 我尝试使用变量设置上下文并更新该变量,但是它没有用。像这样:
//App.svelte
<script>
import {setContext} from 'svelte';
import Name from './components/Name.svelte';
let name = 'John';
setContext('name',name);
function changeName(){
/// how to update context here ?
name = 'Mike'; // Doesn't work!!!
// setContext('name',name);// Doesn't work - Errors
}
</script>
<Name></Name>
<button on:click={changeName}>Change Name</button>
//Name.svelte
<script>
import {getContext} from 'svelte';
let name = getContext('name');
</script>
<h1> My name is: {name}</h1>
答案 0 :(得分:1)
使用store:
//App.svelte
<script>
import {setContext} from 'svelte';
import {writable} from 'svelte/store';
import Name from './components/Name.svelte';
let name = writable('John');
setContext('name',name);
function changeName(){
$name = 'Mike';
}
</script>
<Name></Name>
<button on:click={changeName}>Change Name</button>
//Name.svelte
<script>
import {getContext} from 'svelte';
let name = getContext('name');
</script>
<h1> My name is: {$name}</h1>
演示:https://svelte.dev/repl/432d3449cd9b4e5d99a303fa143b3dbc?version=3.6.7