🔥 (#149) Controlled Props Pattern, and debugging your templates
Hey!
I've got two extras for you today.
The first is that I'm giving a talk at Vue.js Nation in just a few hours (12:05 EST).
You can get instant access (it's completely free) by going here.
The second is that I've got a new article for you: Controlled Props Pattern
This is a great one for when you need to (sometimes) override the internal state of a component.
I show when you'd want to use it, and how to do it in both the Composition API and the Options API.
Have a great week!
— Michael
Vue Tips Collection
Maybe you just want to stay on top of the latest features, remind yourself of interesting things Vue can do, and get daily inspiration.
Vue Tips Collection is a beautiful book of 115 awesome tips, as well as a daily email to get your creative juices flowing.
🔥 Debugging Templates
If you ever need to debug what's happening inside of a template, you can just throw in a function:
<template> <div v-for="i in 4" :key="i"> {{ log(i) }} {{ i + 1 }} </div> </template>
Vue will execute anything within the curly braces as Javascript, so this function is called normally.
It can be whatever you want. Set it to console.log
if you just want to log out some values:
const log = console.log;
Or add in a debugger
statement so you can step through the code one line at a time and inspect the variables more closely:
const log = (val) => { debugger; };
If we want global access to a debugging utility, we can use the globalProperties
field on our app config:
app.config.globalProperties.$log = console.log;
Now, we can use this $log
method in whatever component we want:
🔥 Reusing Code and Knowledge
Don't Repeat Yourself — an acronym that many know but many don't correctly understand.
DRY isn't actually about code, it's about the knowledge and decisions that are contained in the code. Too often we are just pattern matching on syntax, and that leads us to bad abstractions that should never exist.
Here are some ways we can fix that:
- Don't Repeat Yourself (DRY) — Use components and composables to create reusable views and logic. Doing this well is an entire topic all on it's own, which is why I created a whole course on it.
- Optimize for Change — Most of our time is spent modifying existing code, so it pays to make it easy. If code is new or likely to change, don't worry about abstracting it into a new component yet — duplication is welcome here.
- Syntax vs. Knowledge — When removing duplication or "drying up" your code, make sure you're encapsulating knowledge and not syntax. Just because code looks the same doesn't mean it is the same.
🔥 SSR Safe Directives
In many cases, we need to generate unique IDs for elements dynamically.
But we want this to be stable through SSR so we don't get any hydration errors.
And while we're at it, why don't we make it a directive so we can easily add it to any element we want?
Here's a stripped-down version of this directive:
const generateID = () => Math.floor(Math.random() * 1000); const directive = { getSSRProps() { return { id: generateID() }; }, }
When using it with Nuxt, we need to create a plugin so we can register the custom directive:
// ~/plugins/dynamic-id.ts const generateID = () => Math.floor(Math.random() * 1000); export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.directive("id", { getSSRProps() { return { id: generateID() }; }, }); });
Normally, custom directives are ignored by Vue during SSR because they typically are there to manipulate the DOM. Since SSR only renders the initial DOM state, there's no need to run them, so they're skipped.
But there are some cases where we actually need the directives to be run on the server, such as with our dynamic ID directive.
That's where getSSRProps
comes in.
It's a special function on our directives that is only called during SSR, and the object returned from it is applied directly to the element, with each property becoming a new attribute of the element:
getSSRProps(binding, vnode) { // ... return { attribute, anotherAttribute, }; }
📜 Prisma with Nuxt 3: Getting Data with Prisma (4 of 5)
We've got our database filled with data — now we need to fetch that data.
Prisma gives us a ton of flexibility and power in how we do that.
We can easily make complex queries, all while keeping everything typesafe — you just have to know a couple tricks to get it to work correctly.
In this fourth article in the series, I'll show you how to get data from your database using Prisma.
Check it out here: Prisma with Nuxt 3: Getting Data with Prisma (4 of 5)
💬 The Code You Don't Write
"The code you write makes you a programmer. The code you delete makes you a good one. The code you don't have to write makes you a great one." — Mario Fusco
🧠 Spaced-repetition: Refresh a Page in Vue
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.
If you need to force a reload your entire page using Vue, all you need is some Javascript:
window.location.reload();
But this is a code smell — you should almost never need to use this method.
Instead, a better solution might be one of these:
- Create a method to reset and initialize state instead of relying on
onMounted
hooks or the top-level ofsetup
. You can also create aninitialize
action for Pinia. - Make sure your important state is reactive. This tends to fix a lot of common issues.
- Key-changing — by changing just the
key
attribute on a specific component, you can force just one component to reload instead of your entire app. Still a bit of a hack, but it gets the job done.
p.s. I also have four products/courses: Clean Components Toolkit, Vue Tips Collection 2, Mastering Nuxt 3, and Reusable Components
评论
发表评论