MST
星途 面试题库

面试题:Svelte中模块上下文、Slot与Action的基础应用

在Svelte项目中,假设有一个父组件`Parent.svelte`和一个子组件`Child.svelte`。请描述如何在`Child.svelte`中通过模块上下文传递数据给`Parent.svelte`,并在`Parent.svelte`中接收处理。同时,在`Child.svelte`中使用Slot来嵌入来自`Parent.svelte`的自定义内容,并给`Child.svelte`的某个DOM元素添加一个简单的Action,使其在页面加载时改变背景颜色。请写出关键代码片段及解释。
38.0万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

1. 在Child.svelte中通过模块上下文传递数据给Parent.svelte

Child.svelte

<script>
    // 使用setContext来传递数据
    import { setContext } from 'svelte';
    const dataToParent = 'Hello from Child';
    setContext('childData', dataToParent);
</script>

{#if false}
    <!-- 避免此部分内容渲染,只是为了展示数据传递逻辑 -->
    <Parent /> 
{/if}

解释:在Child.svelte中,通过import { setContext } from'svelte';导入setContext函数,然后使用setContext将数据dataToParent以键'childData'传递出去。这里使用{#if false}包裹<Parent />只是为了展示逻辑,实际不会渲染Parent组件。

Parent.svelte

<script>
    import { getContext } from'svelte';
    const receivedData = getContext('childData');
</script>

<p>{receivedData}</p>

解释:在Parent.svelte中,通过import { getContext } from'svelte';导入getContext函数,然后使用getContext('childData')获取Child.svelte传递过来的数据,并在页面上显示。

2. 在Child.svelte中使用Slot嵌入来自Parent.svelte的自定义内容

Child.svelte

<div>
    <slot></slot>
</div>

解释:Child.svelte中使用<slot>标签来定义插槽,这样在Parent.svelte中引入Child.svelte时,放在<Child>标签之间的内容会被渲染到这个插槽位置。

Parent.svelte

<Child>
    <p>This is custom content from Parent</p>
</Child>

解释:在Parent.svelte中,在<Child>标签之间添加自定义内容,这些内容会显示在Child.svelte的插槽位置。

3. 给Child.svelte的某个DOM元素添加一个简单的Action使其在页面加载时改变背景颜色

Child.svelte

<script>
    const changeBgColor = node => {
        node.style.backgroundColor = 'lightblue';
        return {
            destroy() {
                node.style.backgroundColor = 'initial';
            }
        };
    };
</script>

<div use:changeBgColor>
    <slot></slot>
</div>

解释:首先在Child.svelte<script>部分定义了一个名为changeBgColor的Action函数。该函数接收一个node参数,即应用该Action的DOM元素。在函数内部,将元素的背景颜色设置为lightblue。同时返回一个对象,对象中的destroy函数在组件销毁时会将背景颜色恢复为初始值。然后在<div>标签上使用use:changeBgColor将这个Action应用到该div元素上,当页面加载时,该div的背景颜色就会变为lightblue