MST
星途 面试题库

面试题:Svelte中Props、Context API与事件派发的基本使用

在Svelte组件中,如何定义和接收Props?请举例说明。同时简述Context API是如何在组件树中传递数据的,以及如何通过事件派发机制在父子组件间通信。
40.8万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

定义和接收Props

在Svelte组件中,定义和接收Props非常简单。假设我们有一个 MyComponent.svelte 组件,想要接收一个 name 的Prop。

  1. 定义Props:在组件的脚本部分,使用 export 关键字定义Props。
<script>
    export let name;
</script>

<p>Hello, {name}!</p>
  1. 传递Props:在父组件中使用 MyComponent 时传递Prop。
<script>
    import MyComponent from './MyComponent.svelte';
</script>

<MyComponent name="John" />

Context API传递数据

  1. 设置Context:使用 setContext 函数在组件中设置上下文数据。例如,在 Parent.svelte 组件中:
<script>
    import { setContext } from'svelte';
    const theme = 'dark';
    setContext('theme', theme);
</script>

<Child />
  1. 获取Context:子组件可以使用 getContext 函数获取上下文数据。在 Child.svelte 组件中:
<script>
    import { getContext } from'svelte';
    const theme = getContext('theme');
</script>

<p>The theme is {theme}</p>

Context API 允许在组件树中共享数据,不必通过层层传递Props,适合共享一些全局或跨层级的数据。

事件派发机制在父子组件间通信

  1. 子组件派发事件:在子组件 Child.svelte 中,使用 createEventDispatcher 来创建事件派发器。
<script>
    import { createEventDispatcher } from'svelte';
    const dispatch = createEventDispatcher();
    function handleClick() {
        dispatch('customEvent', { message: 'Button clicked' });
    }
</script>

<button on:click={handleClick}>Click me</button>
  1. 父组件监听事件:在父组件 Parent.svelte 中监听子组件派发的事件。
<script>
    import Child from './Child.svelte';
    function handleCustomEvent(event) {
        console.log(event.detail.message);
    }
</script>

<Child on:customEvent={handleCustomEvent} />

通过这种方式,子组件可以通过派发事件向父组件传递数据和通知父组件执行某些操作。