DEV Community

Cover image for ตรวจสอบค่า slot ด้วย $$slots ใน Svelte3
thinny
thinny

Posted on

ตรวจสอบค่า slot ด้วย $$slots ใน Svelte3

เมื่ออ่านมาถึงบทนี้ ก็คงจะพอรู้และการใช้งาน slot มาพอสมควรแล้วคราวนี้เรามาลองตรวจค่าจาก slot กันหน่อย

สืบเนื่องจาก slot มีการกหนด fallback ได้ ปัญหาในเรื่องนี้คือ เมื่อเราไม่กไหนดค่าให้ slot default แต่ slot ก็ยังค่า fallback content อยู่ดี ถ้่าหากเราต้องการตรวจสอบค่าจาก slot นั้นก่อนจะทำอย่างไร มาดูกันครับ

/* Comment.svelte */
<div class="discussion">
  <h3>Comments</h3>
  <slot name="comment">
    default slot
  </slot>
</div>

/* App.svelte */
<script>
  import Comment from "Comment.svelte";
</script>

<Comment>
  <span slot="comment">Title Comment</span>
</Comment>

<Comment />

Enter fullscreen mode Exit fullscreen mode

ผลลัพธ์
Alt Text

แต่ถ้าเราอยาก check ค่า slot ก่อนว่ามีการส่งค่า named slot มาไหมแล้วค่อยแสดง content ได้ เราสามารถใช้ $$slots ตรวจสอบค่าได้

/* Comment.svelte */

{#if $$slots.comment}
<div class="discussion">
  <h3>Comments</h3>
  <slot name="comment">
    default slot
  </slot>
</div>
{/if}

Enter fullscreen mode Exit fullscreen mode

ผลลัพธ์
Alt Text

ถ้าเราไม่ได้ส่ง named slot เข้าไปมันก็ไม่แสดง fallback content ออกมาแล้ว
ลองไปปรับใช้กันนะครับ

ศึกษาเพิ่มเติมเรื่อง slot tag ได้ที่ slot tag

หากสนใจ svelte สามารถเรียนรู้การใช้งาน svelte แบบ step by step ได้ที่
Svelte: Framework Not Framework — (ตอนที่ 1) แรกรู้จัก

ขอบคุณทุกท่านที่อ่านมาถึงตรงนี้ ถ้าอ่านแล้วรู้มีประโยชน์ ฝากกด Subscribe หรือ share link ให้คนอื่นรับรู้ด้วยนะครับ ขอบคุณครับ

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay