If you like Anthony's newsletter on Vue.js Developers, you'll enjoy this one, too.
Join 13,567+ other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.
đź‘‹Hey friend! I work hard to send you amazing stuff each week.
— Michael
Hey all!
Not a lot new from me this week, but I've got some JS and Vue tips for you, like always.
Enjoy your week!
— Michael
Proxies are one of the strangest but most interesting parts of Javascript.
It's a fancy wrapper that lets us create lightweight reactivity systems like in Vue, and so much more.
Defining a proxy is simple. We just need to create a handler object, and then use it on an object:
const handler = {get(target, prop, receiver) {return 'proxied!';},};const someObj = {hello: 'world',};const proxy = new Proxy(someObj, handler);console.log(proxy.hello) // proxied!
It lets us intercept property accesses with the get "trap", so we could force any object to use our own logging method:
const handler = {get(target, prop, receiver) {return () => {if (typeof target[prop] !== "function") return;// Force the method to use our own logging methodconst consoleLog = console.log;console.log = (msg) => {consoleLog(`[${prop}] ${msg}`);};target[prop]();console.log = consoleLog;};},};const someObj = {hello() {console.log('world');}}const proxy = new Proxy(someObj, handler);proxy.hello() // [hello] world
We can also intercept when a property is set, prototypes are accessed, and many more things.
You can find a complete list on MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
When using slots in Vue, you might want to apply default styling to ensure consistent appearance across uses.
Instead of requiring slot content to be wrapped every time, you can include the styling wrapper within the slot's component:
<!-- StyledSlot.vue --><template><div class="default-styles"><slot /></div></template>
Now, when you use the StyledSlot
component, the default styles are automatically applied without extra markup:
<template><StyledSlot>Slot content with default styling</StyledSlot></template>
It's a simple thing, but it makes a difference across a whole app.
Be mindful of the type of slot you're creating—layout slots should not include styling, while content slots should.
This practice prevents unnecessary CSS from complicating your layout and ensures a clean, consistent look for your components' content.
In Nuxt we can get detailed information on how our page is loading with the useLoadingIndicator
composable:
const {progress,isLoading,} = useLoadingIndicator();console.log(`Loaded ${progress.value}%`); // 34%
It’s used internally by the <NuxtLoadingIndicator>
component, and can be triggered through the page:loading:start
and page:loading:end
hooks (if you’re writing a plugin).
But we have lots of control over how the loading indicator operates:
const {progress,isLoading,start, // Start from 0set, // Overwrite progressfinish, // Finish and cleanupclear // Clean up all timers and reset} = useLoadingIndicator({duration: 1000, // Defaults to 2000throttle: 300, // Defaults to 200});
We’re able to specifically set the duration
, which is needed so we can calculate the progress
as a percentage. The throttle
value controls how quickly the progress
value will update — useful if you have lots of interactions that you want to smooth out.
The difference between finish
and clear
is important. While clear
resets all internal timers, it doesn’t reset any values.
The finish
method is needed for that, and makes for more graceful UX. It sets the progress
to 100
, isLoading
to true
, and then waits half a second (500ms). After that, it will reset all values back to their initial state.
Both are used to wait for the DOM to update, but they do it in different ways. We'll explore the differences between them and what it all means.
Check it out here: The Difference Between a Post Flush Watcher and nextTick in Vue
Learn how to write bulletproof watchers in Vue, when to use onCleanup and onWatcherCleanup, and how to build reusable cleanup helpers.
Check it out here: Bulletproof Watchers in Vue
"The purpose of software engineering is to control complexity, not to create it." — Unkown
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.
It's possible to add global properties to your Vue app in both Vue 2 and Vue 3:
// Vue 3const app = createApp({});app.config.globalProperties.$myGlobal = 'globalpropertiesftw';// Vue 2Vue.prototype.$myGlobal = 'globalpropertiesftw';
I would recommend prefixing any global properties with a $
.
This helps prevent naming conflicts with other variables, and it's a standard convention that makes it easy to spot when a value is global.
This global property can be accessed directly off of any component when using the Options API:
computed: {getGlobalProperty() {return this.$myGlobal;},},
Why can't this be used with the composition API?
Because the composition API is designed to be context-free and has no access to this
.
Instead, you can create a simple composable to access your globals:
<script setup>import useGlobals from './useGlobals';const { $myGlobal } = useGlobals();</script>
// useGlobals.jsexport default () => ({$myGlobal: 'globalpropertiesftw',});
Michael Hoffman curates a fantastic weekly newsletter with the best Vue and Nuxt links.
p.s. I also have a bunch of products/courses: