Read this on my blog This has been a very exciting week! The Nuxt 4 alpha is out, and the stable version will be here by the end of the month. You can read all about it in the announcement blog post. The timing could not be better, either. The official course on learning Nuxt 4 will be completed only weeks later. I'm currently recording the last set of lessons for Mastering Nuxt: Full Stack Unleashed. It's currently in early access, with 75+ lessons already released. Right now, you can get it at the discounted early access price until it's finished. Also, if you use the code NUXTLEVEL you can get an extra $30 off this week! Now, back to your regular tips. — Michael Clean Components Toolkit Are your Vue components getting messy and hard to maintain? Struggling with when to split components or how to organize your code? The Clean Components Toolkit teaches you battle-tested patterns and principles to write cleaner, more maintainable Vue apps, including: - 3.5 + hours of focused video content plus comprehensive written materials
- Step-by-step refactoring examples showing real-world applications
- Interactive quizzes to reinforce your learning
- 20 + practical tools and patterns for component organization
- Lifetime access to updates and new content
You'll master: - Component splitting and combining — when (and when not) to break up components
- State management across components — especially as complexity grows
- Logic organization and reuse — using the three core component types
- Seamless refactoring techniques — transform messy code into clean, maintainable components
"The Clean Components Toolkit's concise, to-the-point lessons made the learning process feel effortless and led to a deeper understanding of the subject matter." — Alex Rodriguez Master Clean Components Now → 🔥 Ref vs. Reactive Is it better to use ref or reactive when using the composition API? Here are a few situations where ref is better than reactive . Using ref on objects makes it clear where an object is reactive and where it's just a plain object: // I can expect this ref to update reactively if (burger.value.lettuce) { // ... } // I have no clue if this value is reactive if (burger.lettuce) { // ... }
When using one of the watch methods, refs are automatically unwrapped, so they're nicer to use: // Ref const refBurger = ref({ lettuce: true }); watch( // Not much, but it's a bit simpler to work with refBurger, () => console.log("The burger has changed"), { deep: true } ); // Reactive const reactiveBurger = reactive({ lettuce: true }); watch( reactiveBurger, () => console.log("The burger has changed"), );
One last reason why refs make more sense to me — you can put refs into a reactive object. This lets you compose reactive objects out of refs and still use the underlying refs directly: const lettuce = ref(true); const burger = reactive({ // The ref becomes a property of the reactive object lettuce, }); // We can watch the reactive object watchEffect(() => console.log(burger.lettuce)); // We can also watch the ref directly watch(lettuce, () => console.log("lettuce has changed")); setTimeout(() => { // Updating the ref directly will trigger both watchers // This will log: `false`, 'lettuce has changed' lettuce.value = false; }, 500);
🔥 How to Watch Props for Changes With the Composition API, we have several great options for watching props. The recommended approach would be using either watch or watchEffect in your script setup : import { watch, watchEffect } from "vue"; const props = defineProps<{ count: number }>(); watch( () => props.count, (val) => { console.log(val); } ); watchEffect( () => console.log(props.count) );
Script Setup + Composition API When using the watch method, we have to provide a getter function instead of passing the value directly. This is because the prop object itself is reactive, but the individual props are not. You can test this for yourself by passing in the reactive prop object directly: watch( props, (val) => { console.log(val); } );
The difference between watch and watchEffect is that watch requires us to specify exactly what we're watching, while watchEffect will simply watch every value that is used inside of the method that we pass to it. So we have a tradeoff between simplicity and flexibility. Composition API + Options API If you're using the setup() function within the Options API, the only difference is in how we specify the props. Otherwise, everything else works exactly the same: import { watch, watchEffect } from "vue"; export default { props: { count: { type: Number, required: true, }, }, setup(props) { watch( () => props.count, (val) => { console.log(val); } ); watchEffect(() => console.log(props.count)); }, };
Options API The process is straightforward with the Options API. Just use the name of the prop as the name of the watcher, and you're good to go! export default { props: { count: { type: Number, required: true, }, }, watch: { count(val) { console.log(val); }, }, };
Although this syntax is simpler than the Composition API syntax, the tradeoff is that there is far less flexibility. If you want to watch multiple things at once, or have any fine-grained control over the dependencies, the Composition API is much easier to use. 🔥 Creating an If...Else Component Ever thought about making an If...Else component in Vue, despite having v-if , v-else , and v-else-if ? Here's a quirky experiment that explores this idea: <If :val="mainCondition"> <template #true>Render if true</template> <Else :if="false">Else if condition</Else> <template #false>Otherwise render this</template> </If>
This setup uses Compound Components, default and named slots, and even render functions to achieve a flexible If...Else logic. The If component checks a condition and decides which slot (true , false , or Else ) to render. The Else component — a Compound Component — allows for an else if condition. I have a detailed write up about this component on my blog. Here's a simplified version for a cleaner API: <If :val="condition"> <True>Truth</True> <Else :if="elseCondition">Else slot</Else> <False> What up false branch! </False> </If>
This experiment is a fun way to dive deep into Vue's features like slots, reactivity, and component communication. While it might not replace the built-in directives, it's a great learning exercise and could inspire other creative component designs. Check out the demo and maybe even try implementing your version: Vue If...Else Component Demo Remember — experimenting with "weird" ideas is a fantastic way to deepen your understanding of Vue! 🎙️ Recent DejaVue Episodes There isn't a new episode this week, but here are the last episodes from the past few weeks: 📜 Quick Pinia Overview (video) This video from LearnVue shows you the most essential bits of Pinia. Pinia is the official state management library for Vue 3, so it's definitely worth taking some time to understand it! Check it out here: Quick Pinia Overview (video) 📜 Ref vs Reactive — Which is Best? This has been a question on the mind of every Vue dev since the Composition API was first released: What's the difference between ref and reactive, and which one is better? In this article, I explore this question in detail, comparing ref and reactive, giving my own opinion, and sharing other opinions from the community. Check it out here: Ref vs Reactive — Which is Best? 💬 Mass producing software "You can mass-produce hardware; you cannot mass-produce software; you cannot mass-produce the human mind." — Michio Kaku 🧠 Spaced-repetition: From Options to Composition — The Easy Way 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. You can use reactive to make the switch from the Options API a little easier: // Options API export default { data() { username: 'Michael', access: 'superuser', favouriteColour: 'blue', }, methods: { updateUsername(username) { this.username = username; }, } };
We can get this working using the Composition API by copying and pasting everything over using reactive : // Composition API setup() { // Copy from data() const state = reactive({ username: 'Michael', access: 'superuser', favouriteColour: 'blue', }); // Copy from methods updateUsername(username) { state.username = username; } // Use toRefs so we can access values directly return { updateUsername, ...toRefs(state), } }
We also need to make sure we change this → state when accessing reactive values, and remove it entirely if we need to access updateUsername . Now that it's working, it's much easier to continue refactoring using ref if you want to — or just stick with reactive . 🔗 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: |
评论
发表评论