在 addEventListener 消息之后将新项目附加到 Div 容器中的 svelte

Append new Item to Div Container in svelte after addEventListener Message

如您所见,我已经创建了一个组件。我正在向我的脚本报告我正在侦听 window 事件侦听器(消息)。我实际上想在每次调用此 EventListnere 时,在金色通知框下添加一个新的通知。我如何将其存档在 svelte 中。 ?

<script>

    import Notification from './Components/Notification.svelte';
    let type,text,time,title,icon,position,top,progress
    let slideIn = true;
    let showNoti;
    $: if(!slideIn) {
        slideIn === false;
    } 

window.addEventListener('message', (event) => {
    showNoti = true;
    if(showNoti) {

        let data = event.data;
        type = data.type
        text = data.text
        time = data.time
        title = data.title
        icon = data.icons;
        top = data.top;
        progress = data.progress;
        position = data.position;
        if(type == "success") {
            type = "success"
        }else if(type == "error") {
            type = "error"
        }else if(type == "money") {
            type = "money"
        }
        setTimeout(() => {
            slideIn = false;
        }, time);
    }
});



</script>


<main> 
{#if showNoti}
    <div class="notif-container {position}" style="top: {top}">
        <div class="notify_box">
                <Notification text={text} type={type} time={time} title={title} icon={icon} position={position} top={top} progress={progress} slideIn={slideIn} />
          </div>
    </div>

{/if}

</main>

<style>
    
</style>

如果你想有一系列的通知块,你需要使用一个数组。将通知添加到此数组并简单地遍历它以显示它们。

<script>
let notifications = []

window.addEventlistener() {
  // create here a new notifications object and add it to the array
  // make sure to have an assignment to 'notifications'
  notifciation = [...notifications, newNotification];
}
</script>

{#each notification as notification}
  <!-- add markup here -->
  <Notification {...notification} />
{/each}

这里的代码使用{...notification}将道具传递给组件,只要组件上的属性和对象中的属性完全相同就可以工作.