Hey!
I have a bunch of stuff to share this week.
VueConf Toronto is coming up in November!
I'll be there, talking about Nuxt layers. Come out and say hi! It will be a ton of fun!
Get tickets here (use code DEJAVUE
for a discount!): VueConf Toronto
I'm also giving a talk at Nuxt Nation (it will be a different talk). This one is free, but sign up so you don't forget.
In other news, the first session of Advanced Frontend Testing went very well. I'm really excited to finish this material and then turn it into a course for you.
Pre-orders will be opening early December, maybe a bit sooner. We'll see how productive I am (and how overly optimistic those timelines are)
As always, I've got tips, articles, and a new podcast for you!
— Michael
A composable can either return a single value or an object of values. Typically, these values are refs
.
But we can also dynamically switch between the two depending on what we want to use the composable for:
// Grab only the single valueconst now = useNow()// Get more granular access to the composableconst {now,pause,resume} = useNow({ controls: true })
This is great because we may only need a single value most of the time. So why complicate the interface for the main use case?
But by dynamically providing the full object of ref
s, we allow for more advanced use cases as well. Even if they are rarely used.
Here is how we might implement that:
export default useNow(opts) {const {controls = false,} = opts;// Do some things in your composableif (controls) {return { now, pause, resume };} else {return now;}}
You don’t have to decide between Options API and Composition API, you can use both:
export default {setup() {const darkMode = ref(false);return { darkMode }},methods: {saveDarkMode() {localStorage.setItem('dark-mode', this.darkMode);},}};
Although you can access Composition API from the Options API, it’s a one-way street. The Composition API cannot access anything defined through the Options API:
export default {setup() {const darkMode = ref(false);return { darkMode }},methods: {changeTheme(val) {// This WILL NOT access the ref defined abovethis.darkMode = val;}}};
This can be useful for incremental adoption of the Composition API, because it lets you use reusable composables in your Options API.
But mixing two styles of writing components is likely to cause more headaches than it solves, so please think twice before doing this!
Props down, events up. That's how your components should communicate — most of the time.
But in rare cases, that just doesn't work.
If you need direct access to the parent component, you should just use provide
/inject
to pass down the relevant value or method:
import { provide } from 'vue';const someMethodInTheParent = () => {};provide('method', someMethodInTheParent)
Then, inject it into the child component:
import { inject } from 'vue';const method = inject('method');method();
In Vue 2, you can also use the instance property $parent
:
// Tight coupling like this is usually a bad ideathis.$parent.methodOnParentComponent();
This is simpler, but leads to higher coupling and will more easily break your application if you ever refactor.
You can also get direct access to the application root, the very top-most component in the tree, by using $root
. Vue 2 also has $children
, but these were taken out for Vue 3 (please don't use this one).
When would these be useful?
There are a few different scenarios I can think of. Usually, when you want to abstract some behaviour and have it work "magically" behind the scenes.
You don't want to use props and events to connect up a component in those cases. Instead, you use provide
/inject
, $parent
, or $root
, to automatically connect the components and make things happen.
(This is similar to the Compound Component pattern)
But it's hard to come up with an example where this is the best solution. Using provide
/inject
is almost always the better choice.
Vue is fast (actually the fastest SSR framework)! But sometimes apps might a bit more fine-tuning. And by sometimes, we mean rarely.
Still, it can happen - so join Alex and Michael in this DejaVue episode to dive into what tools Vue gives us to improve the frameworks' performance.Â
Further, they dive into the recent SSR benchmark and what it means for you as a developer, as well as striving topics like perceived performance.Â
Enjoy the episode!Â
Watch on YouTube or listen on your favorite podcast platform.
Chapters:
In case you missed them:
I hate thinking.
Well, actually, I love thinking, but only when I’m able to solve problems or make progress with it.
But often our code gets in the way of this. And as one workshop attendee said about reading code, “if you’re confused, it’s not your fault.”
This article goes over some ways you can make your code easier to think about, so you’re less confused and can actually get stuff done.
Check it out here: Make Your Components Easier to Think About
In this article I share 21 tips for working with Nuxt.
These are tips and tricks that I've found useful, and I think every Nuxt developer should know.
We cover a lot of topics here, including:
Check it out here: 21 Nuxt Tips You Need to Know
Here are some upcoming events you might be interested in. Let me know if I've missed any!
My favourite Vue conference, in my own backyard! A three-day event with workshops, speakers from around the world, and socializing.
The biggest Vue conference in the world! A two-day event with workshops, speakers from around the world, and socializing.
"Good code is its own best documentation. As you're about to add a comment, ask yourself, 'How can I improve the code so that this comment isn't needed?'" — Steve McConnell
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 call a method from outside of a component by giving it a ref
:
<!-- Parent.vue --><template><ChildComponent ref="child" /></template><script setup>const child = ref(null);// Somewhere in the Parent componentchild.value.method();</script>
If you're using the Options API, your syntax is only slightly different:
<!-- Parent.vue --><template><ChildComponent ref="child" /></template><script>export default {methods: {myMethod() {// This can be anywhere in the Parent componentthis.$refs.child.method();}}}</script>
Let me explain this one a bit more.
Sometimes "best practices" don't work for what you're doing, and you need an escape hatch like this.
Typically, we communicate between components using props and events. Props are sent down into child components, and events are emitted back up to parent components.
<template><ChildComponent:tell-me-what-to-do="someInstructions"@something-happened="hereIWillHelpYouWithThat"/></template>
Occasionally, you may need your parent to trigger a method in the child component. This is where only passing props down doesn't work as well.
You could pass a boolean down and have the child component watch it:
<!-- Parent.vue --><template><ChildComponent :trigger="shouldCallMethod" /></template><script setup>// Child.vueimport { watch } from 'vue';const props = defineProps({trigger: {type: Boolean,required: true}});watch(props.trigger, (newVal) => {if (newVal) {// Call the method when the trigger is set to `true`someMethodInChild();}});</script>
This works fine, but only on the first call. If you needed to trigger this multiple times, you'd have to clean up and reset the state. The logic would then look like this:
true
to trigger
proptrigger
back to false
, so we can do this all over againUgh.
Instead, if we set a ref
on the child component we can call that method directly:
<!-- Parent.vue --><template><ChildComponent ref="child" /></template><script setup>const child = ref(null);// Somewhere in the Parent componentchild.value.method();</script>
Yes, we're breaking the "props down, events up" rule and breaking encapsulation, but it's so much cleaner and easier to understand that it's worth it!
Sometimes the "best" solution ends up being the worst solution.
Michael Hoffman curates a fantastic weekly newsletter with the best Vue and Nuxt links.
p.s. I also have four products/courses: Clean Components Toolkit, Vue Tips Collection 2, Mastering Nuxt 3, and Reusable Components