简体   繁体   English

svelte中如何更新上下文?

[英]How to update context in svelte?

getContext and setContext functions can only be called during component initialization. getContext和setContext函数只能在组件初始化期间调用。 Is there some way to update the context value during runtime, on a click event for instance. 是否有某种方法可以在运行时(例如,单击事件)期间更新上下文值。 Imagine we store a theme or a localization in a context value and want to create a button to change that. 假设我们将主题或本地化存储在上下文值中,并希望创建一个按钮来更改它。 Is it possible somehow? 有可能吗? I've tried set the context using a variable and updating that variable, but it didn't work. 我尝试使用变量设置上下文并更新该变量,但是它没有用。 Like this: 像这样:

//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>

Use a 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>

Demo: https://svelte.dev/repl/432d3449cd9b4e5d99a303fa143b3dbc?version=3.6.7 演示: https : //svelte.dev/repl/432d3449cd9b4e5d99a303fa143b3dbc?version=3.6.7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM