【问题标题】:How to update context in svelte?如何在 svelte 中更新上下文?
【发布时间】:2019-07-11 14:16:45
【问题描述】:

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>

【问题讨论】:

    标签: svelte


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 2020-03-16
      • 1970-01-01
      • 2020-04-27
      • 2021-08-12
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多