温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Svelte组件之间传递数据和事件

发布时间:2024-06-15 17:13:36 来源:亿速云 阅读:131 作者:小樊 栏目:web开发

在Svelte组件之间传递数据和事件可以通过props和自定义事件来实现。

  1. 通过props传递数据:在父组件中通过props将数据传递给子组件。在子组件中通过props属性来接收传递过来的数据。例如:
<!-- ParentComponent.svelte -->
<script>
    import ChildComponent from './ChildComponent.svelte';

    let data = 'Hello from parent component';
</script>

<ChildComponent data={data} />
<!-- ChildComponent.svelte -->
<script>
    export let data;
</script>

<p>{data}</p>
  1. 通过自定义事件传递数据:在子组件中通过dispatch方法触发自定义事件,并传递数据给父组件。在父组件中监听子组件的自定义事件,并处理传递过来的数据。例如:
<!-- ChildComponent.svelte -->
<script>
    import { createEventDispatcher } from 'svelte';

    const dispatch = createEventDispatcher();

    function sendData() {
        const data = 'Hello from child component';
        dispatch('customEvent', data);
    }
</script>

<button on:click={sendData}>Send Data</button>
<!-- ParentComponent.svelte -->
<script>
    import ChildComponent from './ChildComponent.svelte';

    let receivedData;

    function handleCustomEvent(event) {
        receivedData = event.detail;
    }
</script>

<ChildComponent on:customEvent={handleCustomEvent} />

<p>{receivedData}</p>

通过以上两种方式,可以在Svelte组件之间传递数据和事件。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI