MST

星途 面试题库

面试题:Svelte模块化开发中如何实现组件间通信

在Svelte的模块化开发场景下,假设有一个父组件和多个子组件,描述一下常用的实现组件间通信的方式,并给出简单代码示例。
20.0万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

1. 通过props传递数据(父传子)

  • 原理:父组件通过向子组件传递属性(props)来共享数据。
  • 代码示例
    • 父组件(Parent.svelte)
<script>
  let message = 'Hello from parent';
</script>

<Child {message} />

<script>
  import Child from './Child.svelte';
</script>
  • 子组件(Child.svelte)
<script>
  export let message;
</script>

<p>{message}</p>

2. 通过事件(子传父)

  • 原理:子组件通过createEventDispatcher创建事件分发器,然后触发自定义事件,父组件监听这些事件来接收子组件的数据。
  • 代码示例
    • 父组件(Parent.svelte)
<script>
  function handleChildEvent(data) {
    console.log('Received from child:', data);
  }
</script>

<Child on:childEvent={handleChildEvent} />

<script>
  import Child from './Child.svelte';
</script>
  • 子组件(Child.svelte)
<script>
  import { createEventDispatcher } from'svelte';
  const dispatch = createEventDispatcher();
  function sendDataToParent() {
    const data = 'Some data from child';
    dispatch('childEvent', data);
  }
</script>

<button on:click={sendDataToParent}>Send data to parent</button>

3. 上下文API(适用于多层嵌套组件通信)

  • 原理:使用setContext在父组件中设置上下文数据,子组件通过getContext获取该上下文数据,从而实现通信。
  • 代码示例
    • 父组件(Parent.svelte)
<script>
  import { setContext } from'svelte';
  const sharedData = { value: 'Shared context data' };
  setContext('sharedContext', sharedData);
</script>

<GrandChild />

<script>
  import GrandChild from './GrandChild.svelte';
</script>
  • 子组件(GrandChild.svelte)
<script>
  import { getContext } from'svelte';
  const sharedData = getContext('sharedContext');
</script>

<p>{sharedData.value}</p>

4. 存储(适用于跨组件通信)

  • 原理:使用Svelte的writable存储来共享数据,不同组件可以订阅和修改这个存储的值。
  • 代码示例
    • 创建存储(store.js)
import { writable } from'svelte/store';
export const sharedStore = writable('Initial value');
  • 组件1(Component1.svelte)
<script>
  import { sharedStore } from './store.js';
  function updateStore() {
    sharedStore.update(value => 'New value from Component1');
  }
</script>

<button on:click={updateStore}>Update store from Component1</button>
  • 组件2(Component2.svelte)
<script>
  import { sharedStore } from './store.js';
  let value;
  sharedStore.subscribe(newValue => {
    value = newValue;
  });
</script>

<p>{value}</p>