The magic of scoped slots in Vue ✨ (3/4)
Hey! In yesterday's email I shared what I think is the key feature to making Vue components highly reusable: Scoped slots. But scoped slots are hard to grasp, and even more difficult to master. So today, we're going to make sure we understand them on a deep, intuitive level. Then, I'm going to introduce you to the magic ✨ of scoped slots. The trick is to think of them as functions. Slots are just functionsWe're going to recreate the functionality of slots, but we'll use a regular Javascript function that only returns HTML. This is the code we'll replicate: We have a First, we'll create a We'll ignore the slot for now. What we get is our "child" component, without the slot. We can add props by simply passing arguments into this new function we've created: But we still haven't replicated the slot yet. We could just have the slot as another argument, treating it like a "special" prop: In fact, this is how regular slots were implemented in Vue 2 — it works, but has drawbacks. We aren't able to replicate scoped slots like this, because there's no way to get data from the Unless, that is, we use a callback function instead: By using a callback function we're able to fully replicate how slots and scoped slots work. Thinking of slots as functions helps to think through how values are being passed around, and gives us a better mental model for them. This is because this is exactly how they're implemented in Vue — using callback functions. The magic of scoped slots ✨Now that we understand what's going on with slots, we can get to the fun stuff. I'm talking about the patterns and tools that let us leverage the power of scoped slots and help us to write better components:
But this email already has a lot of information for a Wednesday, so we'll cover these in tomorrow's email. ...actually, there's a better way to learn this stuff. If you want to learn all of the things I know about scoped slots, plus everything else about building highly reusable components, I just launched a big update to Reusable Components. Reusable Components takes you through the 6 Levels of Reusability. Each level builds on the last, giving you more tools to create more and more flexible and reusable components. There are videos, written content, and step-by-step refactoring examples of real-world code, showing you exactly how to apply these to your own projects. And it's 35% off for the next 7 days! You can check it out here. If you decide not to buy, I'll see you tomorrow for the final email in the series! — Michael |
评论
发表评论