การใช้งาน v-slot slot-scope ใน Vue.js

**การใช้งาน v-slot slot-scope ใน Vue.js**

ใน Vue.js, v-slot และ slot-scope เป็นส่วนสำคัญที่ช่วยให้เราสร้างโค้ดที่มีความยืดหยุ่นและ reusable ได้อย่างง่ายดาย ซึ่งสามารถช่วยให้การจัดการข้อมูลและการแสดงผลของข้อมูลใน component ของเรามีความสะดวกและง่ายขึ้น

**v-slot**
v-slot เป็น directive ที่ใช้สำหรับการ define template ที่แสดงผลใน child component ภายใน parent component โดยส่วนตัวผมชอบเรียกว่า “slot content” การใช้งาน v-slot จะถูกกำหนดไว้ใน tag หรือ element ที่เป็น parent โดยมี syntax ดังนี้
“`

“`

**slot-scope**
slot-scope เป็น attribute ที่ใช้กำหนดค่าหรือข้อมูลที่จะถูกส่งผ่านจาก parent component ไปยัง slot content ภายใน child component โดย syntax จะเหมือนกับการสร้าง template ด้วย v-slot
“`

{{ slotProps.data }}

“`

**ตัวอย่างการใช้งาน**
สำหรับตัวอย่างนี้ เราจะสร้าง parent component ที่มี template สำหรับ render list ของ items ซึ่งเราจะส่งข้อมูล item แต่ละตัวไปยัง slot content ของ child component ด้วยการใช้ v-slot และ slot-scope

**Parent Component**
“`

  • {{ slotProps.item.name }}

import ChildComponent from ‘./ChildComponent.vue’;

export default {
components: {
ChildComponent,
},
data() {
return {
items: [
{ id: 1, name: ‘Item 1’ },
{ id: 2, name: ‘Item 2’ },
{ id: 3, name: ‘Item 3’ },
],
};
},
};

“`

**Child Component (ChildComponent.vue)**
“`

export default {
props: [‘item’],
};

“`

ในที่นี้ parent component จะส่งข้อมูล item ไปยัง child component ผ่านการใช้งาน v-slot และ slot-scope เพื่อให้ child component สามารถแสดงผลข้อมูล item นั้นใน template ของมันเองได้

ดังนั้น v-slot และ slot-scope เป็นเครื่องมือสำคัญที่ช่วยให้เราสร้างโค้ด Vue.js ที่ reusability และ maintainability สูงขึ้นได้อย่างมีประสิทธิภาพ