MST

星途 面试题库

面试题:Svelte模块上下文在组件通信中的应用

请阐述在Svelte中,如何利用模块上下文来实现非父子组件之间的通信,并举例说明实现步骤及关键代码。
20.8万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

1. 模块上下文的概念

在Svelte中,模块上下文可以理解为一个共享的作用域,不同组件可以通过访问这个共享作用域来实现通信。它基于JavaScript模块的单例特性,即无论一个模块被导入多少次,其内部状态都是共享的。

2. 实现步骤

  1. 创建共享模块:创建一个JavaScript模块,用于存储共享状态和通信逻辑。
  2. 在组件中导入共享模块:需要通信的组件导入这个共享模块。
  3. 更新和读取共享状态:在一个组件中更新共享模块的状态,其他组件通过读取共享模块的状态来实现通信。

3. 关键代码示例

  1. 创建共享模块 store.js
// store.js
let sharedValue = 0;

const setSharedValue = (value) => {
    sharedValue = value;
};

const getSharedValue = () => {
    return sharedValue;
};

export { setSharedValue, getSharedValue };
  1. 第一个组件 ComponentA.svelte
<script>
    import { setSharedValue } from './store.js';
    let newVal = 5;
    const updateSharedValue = () => {
        setSharedValue(newVal);
    };
</script>

<button on:click={updateSharedValue}>更新共享值为 {newVal}</button>
  1. 第二个组件 ComponentB.svelte
<script>
    import { getSharedValue } from './store.js';
    let value = getSharedValue();
</script>

<p>共享值为: {value}</p>
  1. 在主组件或父组件中使用这两个组件
<script>
    import ComponentA from './ComponentA.svelte';
    import ComponentB from './ComponentB.svelte';
</script>

<ComponentA />
<ComponentB />

在上述示例中,ComponentA 通过调用 setSharedValue 函数更新共享值,ComponentB 通过调用 getSharedValue 函数读取共享值,从而实现了非父子组件之间的通信。