Read this on my blog Heyo! Today Vue Amsterdam is starting, so I'm going to avoid social media to prevent excess FOMO (let's be real, I won't actually avoid social media). Also, less than two weeks until the new version of Mastering Nuxt is launched! This will be an early access while I finish recording the lessons. I don't want to rush things so I can make sure the lessons are as useful and clear as they can possibly be. I hope you enjoy these tips and enjoy your week, — Michael 🔥 Creating Magic with Context-Aware Components Context-aware components are "magical" — they adapt to what's going on around them automatically, handling edge cases, state sharing, and more. There are 3 main types of context-aware components, but configuration is the one I find most interesting. 1. State Sharing When you break up a large component into smaller ones, they often still need to share state. Instead of pushing that work on whoever's consuming the components, you can make this happen "behind the scenes." To give you more flexibility, you may break up a Dropdown component into Select and Option components. But to make it easier to use, the Select and Option components share the selected state with each other: <!-- Used as a single component for simplicity --> <Dropdown v-model="selected" :options="[]" /> <!-- Split up for more flexibility --> <Select v-model="selected"> <Option value="mustard">Mustard</Option> <Option value="ketchup">Ketchup</Option> <div class="relish-wrapper"> <Option value="relish">Relish</Option> </div> </Select>
2. Configuration Sometimes component behaviour needs to change based on what's going on in the rest of the application. This is often done to automagically handle edge cases that would otherwise be annoying to deal with. A Popup or Tooltip should reposition itself so it doesn't overflow out of the page. But if that component is inside a modal, it should move, so it doesn't overflow out of the modal. This can be done automagically if the Tooltip knows when it's inside a modal. 3. Styling You already create context-aware CSS, applying different styles based on what's happening in parent or sibling elements. .statistic { color: black; font-size: 24px; font-weight: bold; } /* Give some separation between stats that are right beside each other */ .statistic + .statistic { margin-left: 10px; }
CSS variables let us push this further, allowing us to set different values in different parts of the page. 🔥 Dynamic Slot Names We can dynamically generate slots at runtime, giving us even more flexibility in how we write our components: <!-- Child.vue --> <template> <div v-for="step in steps" :key="step.id"> <slot :name="step.name" /> </div> </template>
Each of these slots works like any other named slot. This is how we would provide content to them: <!-- Parent.vue --> <template> <Child :steps="steps"> <!-- Use a v-for on the template to provide content to every single slot --> <template v-for="step in steps" v-slot:[step.name]> <!-- Slot content in here --> </template> </Child> </template>
We pass all of our steps to the Child component so it can generate the slots. Then we use a dynamic directive argument v-slot:[step.name] inside a v-for to provide all of the slot content. When might you need something like this? I can imagine one use case for a complex form generated dynamically. Or a wizard with multiple steps, where each step is a unique component. I'm sure there are more! 🔥 Easily Mock API Routes in Nuxt If you've ever written unit tests, you'll have needed to mock out API endpoints that are used in your components or stores. With @nuxt/test-utils this is really simple, because you get the registerEndpoint utility method: import { registerEndpoint } from '@nuxt/test-utils/runtime'; import userTestData from './userTestData.json'; registerEndpoint('/users/', () => userTestData); // ...tests
You can mock any server route (API endpoint), including external endpoints if you need. 🎙️ #050 — DevRel and IDEs (with Jan-Niklas Wortmann) For episode number 50 (not 51 Alex!), Angular GDE and JetBrains DevRel Jan-Niklas Wortmann joins the show. Together with Michael and Alex they dive into Jan-Niklas' angle of being a DevRel, how framework communities are different and why people should give WebStorm a try. Beyond that, Volar and LSPs are also covered, as well as some new announcements! Watch on YouTube or listen on your favorite podcast platform. Chapters: In case you missed them: 📜 Server Routes in Nuxt Server routes are a powerful feature of Nuxt that allow you to create custom endpoints for your app. In this article I look at the different types of server routes and how to use them. Check it out here: Server Routes in Nuxt 📜 Composition API vs. Options API The Composition API and Options API are two different ways to structure your Vue code. In this article I compare the two in depth, and give my own opinion on which one is best (it's the Composition API). Check it out here: Composition API vs. Options API 📅 Upcoming Events Here are some upcoming events you might be interested in. Let me know if I've missed any! Vuejs Amsterdam 2025 — (TODAY! March 12, 2025 to March 13, 2025) The biggest Vue conference in the world! A two-day event with workshops, speakers from around the world, and socializing. Check it out here VueConf US 2025 — (May 13, 2025 to May 15, 2025) Giving a talk here on component patterns! A great Vue conference, this year held in Tampa. Two days of conference talks, plus a day for workshops. Check it out here MadVue 2025 — (May 29, 2025) It's time to get together in Madrid. Join for a full day of talks, activities, and networking with the Vue.js community and ecosystem. Check it out here 💬 Libraries "Telling a programmer there's already a library to do X is like telling a songwriter there's already a song about love." — Pete Cordell 🧠 Spaced-repetition: A bunch of composable mini tips The best way to commit something to long-term memory is to periodically review it, gradually increasing the time between reviews 👨🔬 Actually remembering these tips is much more useful than just a quick distraction, so here's a tip from a couple weeks ago to jog your memory. Yes, mini tips within a tip. It's meta. Here they are: - Start with the end in mind, and write the return first. Once you know how you want the composable to be used, filling in the implementation details is much easier.
- Use an options object as the parameter. This makes it easy to add new parameters in the future without breaking anything, and you won't mess up the ordering anymore.
- Keep them small. Embrace the UNIX philosophy and make sure each composable only does one thing but does it well.
- Name them consistently with
use_ - Always make sure your reactivity is hooked up before any async logic. By using a
ref of null , you can update those values later when your logic completes. No need to await around. - Use
effectScope to group effects if you have lots of them in your composable. This makes cleaning up your reactivity a lot simpler. - If you have large objects, use
shallowRef instead to prevent Vue from recursively making the whole thing reactive. Of course, you'll need to use triggerRef to trigger any reactive effects for it, but it can improve performance. Some tips on making your composables more flexible: - If you're using a
watch , make immediate and flush configurable - Accept both
refs and primitive values as inputs. By passing the variable through ref , you'll either reuse the existing ref or create a new one. - The same trick works with
unref if what you need in your composable is a primitive and not a ref . 🔗 Want more Vue and Nuxt links? Michael Hoffman curates a fantastic weekly newsletter with the best Vue and Nuxt links. Sign up for it here. p.s. I also have a bunch of products/courses: |
评论
发表评论