Read this on my blog 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 🔥 Dynamic Returns 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 value const now = useNow() // Get more granular access to the composable const { 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 composable if (controls) { return { now, pause, resume }; } else { return now; } }
🔥 Hybrid API: Composition API + Options API 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 above this.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! 🔥 Directly accessing parent components (and why) 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 idea this.$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. 🎙️ #028 — Vue Performance Tips 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: 📜 Make Your Components Easier to Think About 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 📜 21 Nuxt Tips You Need to Know 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: When to use /assets vs. /public directory Using runtimeConfig vs. app.config Understanding how Universal rendering works (and how it's different from SPA and SSR) Check it out here: 21 Nuxt Tips You Need to Know 📅 Upcoming Events Here are some upcoming events you might be interested in. Let me know if I've missed any! Vue Fes Japan 2024 — (October 19, 2024) Check it out here VueConf Toronto 2024 — (November 18, 2024 to November 20, 2024) My favourite Vue conference, in my own backyard! A three-day event with workshops, speakers from around the world, and socializing. Check it out here Vuejs Amsterdam 2025 — (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 💬 Comments "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 🧠 Spaced-repetition: Calling a Method from Outside of the Component 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 component child.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 component this.$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.vue import { 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: - The Parent component passes
true to trigger prop - Watch is triggered, and the Child component calls the method
- The Child component emits an event to tell the Parent component that the method has been triggered successfully
- The Parent component resets
trigger back to false , so we can do this all over again Ugh. 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 component child.value.method(); </script>
|
评论
发表评论