เรียนรู้การใช้งาน v-slot และ slot-scope ใน Vue.js

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

ใน Vue.js, เราสามารถใช้ v-slot และ slot-scope เพื่อทำให้ Component สามารถส่งข้อมูลหรือโค้ด HTML ให้กับ Component ลูกได้โดยง่าย โดย v-slot จะเป็น attribute ที่ใช้เรียกใช้ slot ใน Component แม่ และ slot-scope จะเป็น attribute ที่ใช้เข้าถึงข้อมูลใน slot นั้น ๆ

ตัวอย่างการใช้งาน v-slot และ slot-scope ใน Vue.js ดังนี้

“`html

ชื่อ: {{ slotProps.name }}

อายุ: {{ slotProps.age }}

import ChildComponent fromสล็อต‘./ChildComponent.vue’;

export default {
components: {
ChildComponent
}
}

“`

“`html

export default {
data() {
return {
name: ‘John Doe’,
age: 30
}
}
}

“`

ในตัวอย่างด้านบนจะเห็นว่า ParentComponent มี ChildComponent ซึ่งส่งข้อมูล name และ age ผ่าน v-slot และ slot-scope และ ChildComponent จะนำข้อมูลเหล่านั้นมาแสดงผลใน template ของตัวเอง

ด้วยการใช้งาน v-slot และ slot-scope ใน Vue.js เราสามารถสร้าง Component ที่ใช้งานได้ยืดหยุ่นและมีความสะดวกสบายในการจัดการข้อมูลและโค้ด HTML ได้อย่างมีประสิทธิภาพ