Exactly like the title I mentioned. Slot literally means “Place” always.
- Give me a place in my Vue component
- ok son
Slot is a reservation
Slot in vue is a form of “booking” in the component, later when used, we can put other content into the reserved position. Vue allows us to book as many seats, as many as we want, a conditional home =)))) Each of these places is called a “slot”. Let’s see the following example. with mom for friendly )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!-- mother.vue: bà mẹ xây 1 cái card có 2 thành phần có thể thay đổi là image và name nhé. Mẹ đặt 2 chỗ đấy cho con--> <template> <div class="card"> <div class="card-header"> <slot name="image"> <img class="ava" src="https://i.pravatar.cc/150?img=35" alt="Avatar"> </slot> </div> <div class="card-body"> <slot name="name">Tao la me day.</slot> </div> </div> </template> <script> export default { name: "Mother", data() { return {}; } }; </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!-- son.vue --> Nhưng cu con khi dùng cái card này ko thích kiểu này mà lại muốn ở trên là hiện tên..OMG Cãi mẹ là ko vui rồi. Nhưng ko. Cu cậu chỉ cần làm những gì cu cậu muốn bằng việc là người mẹ đã biết kiểu gì cậu cũng bày trò. Bây giờ c chỉ cần change 2 cái chỗ mà mẹ đã đặt thôi <template> <div id="app" class="container"> <Con> <template slot="ava">Đây là tên con, your handsome son ✌?</template> <template slot="name"> Đây là ảnh của con, your handsome son ✌? <img height="150" width="150" src="https://i.pravatar.cc/150?img=2" alt="Avatar"> </template> </Card> </div> </template> <script> import Con from "./components/Con"; export default { name: "App", components: { Con } }; </script> |
So you changed the component I was born with 2 places that I reserved for you the image and name
Slot name
As the example above, we see that when the slot has a name, and pass the name to the slot, only the slot with that name will be changed, the rest will remain intact. If the slot has no name, all the information will be transferred. into the slot
Slot scope
To transfer data from mother to child, we bind the data we want to pass through slot <slot: name = “du-lieu” />
An example to see the benefits of slot in practice.
When I first received the design from the design side, the modal popup was extremely simple, including only the title, description and the three buttons below. At first glance, we only need 3 prop and an event to fire when clicking the button to change depending on the use case.
But after a while, the design team drew a new bunch, embedded the form, inserted another component into it, yes. Prop does not meet the crazy level of you design. And the way we refactor the modal by slot
By using the slot you will have components with the ability to cook it again and again. Hopefully with this tip, everyone will master the component more flexibly (y).