MST

星途 面试题库

面试题:Svelte中Context API如何实现跨层级组件通信

请详细描述在Svelte中使用Context API实现跨层级组件通信的步骤,包括如何创建上下文、如何在祖先组件中提供上下文以及如何在后代组件中订阅上下文数据。
48.7万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试
  1. 创建上下文
    • 在Svelte中,使用setContextgetContext函数来处理上下文。首先从'svelte'模块中导入setContext函数。例如,在一个名为contextStore.js的文件中(这只是一个示例组织方式):
    import { setContext } from'svelte';
    
    const contextKey ='my - context - key';
    const myContextData = {
        someValue: 'default value',
        someFunction: () => {
            console.log('This is a function in context');
        }
    };
    
    const setMyContext = () => {
        setContext(contextKey, myContextData);
    };
    
    export { setMyContext };
    
  2. 在祖先组件中提供上下文
    • 在祖先组件(假设名为Parent.svelte)中,导入创建上下文的函数并调用它。
    <script>
        import { setMyContext } from './contextStore.js';
        setMyContext();
    </script>
    
    <div>
        <h1>Parent Component</h1>
        {#if true}
            <Child />
        {/if}
    </div>
    
    • 这里的<Child />是后代组件,祖先组件通过调用setMyContext设置了上下文数据,后代组件就可以访问这些数据。
  3. 在后代组件中订阅上下文数据
    • 在后代组件(假设名为Child.svelte)中,从'svelte'模块导入getContext函数,并使用之前定义的上下文键来获取上下文数据。
    <script>
        import { getContext } from'svelte';
        const contextKey ='my - context - key';
        const myContext = getContext(contextKey);
    </script>
    
    <div>
        <h2>Child Component</h2>
        <p>{myContext.someValue}</p>
        <button on:click={myContext.someFunction}>Call function from context</button>
    </div>
    
    • 这样,后代组件就可以通过getContext获取祖先组件提供的上下文数据,并使用这些数据进行相应的操作。