🔥 (#206) Options Object Pattern, v-once, and Nuxt Plugin Dependencies

Read this on my blog

Hey!

This week I started recording the first lessons for Mastering Nuxt.

This is a complete redo, so we're starting from scratch, and building a ChatGPT clone.

(and if you already own Mastering Nuxt 3 you'll get this brand new one for free!)

I've also been working with the team at Vue School on putting together the marketing plan for this course launch. Things are starting to happen, and I can't wait for you to get this course!

Next week I'll be sharing a bit more about what you can expect from the course itself.

Have a great week and enjoy the tips,

— Michael

🔥 Example of a Composable Using the Options Object Pattern

Let's create a useEvent composable that will make it easier to add event listeners.

We'll use the EventTarget.addEventListener method, which require the event and handler parameters. These are the first two required parameters:

export function useEvent(event, handler) {};

But we also need to know which element to target. Since we can default to the window, we'll make this our first option:

export function useEvent(event, handler, options) {    // Default to targeting the window    const { target = window } = options;  };

Then we'll add in onMounted and onBeforeUnmount hooks to setup and clean up our event:

import { onMounted, onBeforeUnmount } from 'vue';    export function useEvent(event, handler, options) {    // Default to targeting the window    const { target = window } = options;      onMounted(() => {      target.addEventListener(event, handler);    });      onBeforeUnmount(() => {      target.removeEventListener(event, handler);    });  };

We can use the composable like this:

import useEvent from '~/composables/useEvent.js';    // Triggers anytime you click in the window  useEvent('click', () => console.log('You clicked the window!'));

The addEventListener method can also take extra options, so let's add support for that, too:

import { onMounted, onBeforeUnmount } from 'vue';    export function useEvent(event, handler, options) {    // Default to targeting the window    const {      target = window,      ...listenerOptions    } = options;      onMounted(() => {      target.addEventListener(event, handler, listenerOptions);    });      onBeforeUnmount(() => {      target.removeEventListener(event, handler, listenerOptions);    });  };

We keep listenerOptions as a pass-through, so we're not coupling our composable with the addEventListener method. Beyond hooking up the event, we don't really care how it works, so there's no point in interfering here.

Now we can take advantage of those extra options:

import useEvent from '~/composables/useEvent.js';    // Triggers only the first time you click in the window  useEvent(    'click',    () => console.log('First time clicking the window!'),    {      once: true,    }  );

This is a pretty basic composable, but by using the Options Object Pattern it's easily configurable and extendable to cover a wide swath of use cases.

If you want to learn more about this pattern (and other composable patterns), check out my new course: Composable Design Patterns.

🔥 v-once

If you've got large chunks of static or mostly static content, you can tell Vue to (mostly) ignore it using the v-once directive:

<template>    <!-- These elements never change -->    <div v-once>      <h1 class="text-center">Bananas for sale</h1>      <p>        Come get this wonderful fruit!      </p>      <p>        Our bananas are always the same price — $ each!      </p>        <div class="rounded p-4 bg-yellow-200 text-black">        <h2>          Number of bananas in stock: as many as you need        </h2>        <p>          That's right, we never run out of bananas!        </p>      </div>        <p>        Some people might say that we're... bananas about bananas!      </p>    </div>  </template>

This can be a helpful performance optimization if you need it.

The v-once directive tells Vue to evaluate it once and never update it again. After the initial update it's treated as fully static content.

Here are the docs for v-once.

🔥 Nuxt Plugin Dependencies

When writing plugins for Nuxt, you can specify dependencies:

export default defineNuxtPlugin({    name: 'my-sick-plugin-that-will-change-the-world',    dependsOn: ['another-plugin']    async setup (nuxtApp) {      // The setup is only run once `another-plugin` has been initialized    }  })

But why do we need this?

Normally, plugins are initialized sequentially — based on the order they are in the filesystem:

plugins/  - 01.firstPlugin.ts    // Use numbers to force non-alphabetical order  - 02.anotherPlugin.ts  - thirdPlugin.ts

But we can also have them loaded in parallel, which speeds things up if they don't depend on each other:

export default defineNuxtPlugin({    name: 'my-parallel-plugin',    parallel: true,    async setup (nuxtApp) {      // Runs completely independently of all other plugins    }  })

However, sometimes we have other plugins that depend on these parallel plugins. By using the dependsOn key, we can let Nuxt know which plugins we need to wait for, even if they're being run in parallel:

export default defineNuxtPlugin({    name: 'my-sick-plugin-that-will-change-the-world',    dependsOn: ['my-parallel-plugin']    async setup (nuxtApp) {      // Will wait for `my-parallel-plugin` to finish before initializing    }  })

Although useful, you don't actually need this feature (probably). Pooya Parsa has said this:

I wouldn't personally use this kind of hard dependency graph in plugins. Hooks are much more flexible in terms of dependency definition and pretty sure every situation is solvable with correct patterns. Saying I see it as mainly an "escape hatch" for authors looks good addition considering historically it was always a requested feature.

🎙️ #048 — AI and Vue.js (with Daniel Kelly and Patrick van Everdingen)

AI is a hot topic in the tech industry, but how does it intersect with Vue.js?

In this special episode, Michael and Alex host a panel at Vue.js Nation 2025 and are joined by two amazing guests:

Patrick van Everdingen, AI Solutions Engineer

Daniel Kelly, Lead Instructor at Vue School

The four developers discuss how AI and Vue can work together. Will we all lose our jobs to AI? How does AI might influence the job market and which tips for Vue.js developers are the most important to know regarding using AI in their projects and workflows? You'll get answers to all these questions, and more in this episode.

Enjoy the Episode!

Watch on YouTube or listen on your favorite podcast platform.

Chapters:

In case you missed them:

📜 Configuration in Nuxt: runtimeConfig vs. appConfig

Nuxt provides powerful configuration options, allowing you to adapt your application to different use cases.

The two key parts of Nuxt's configuration system are runtimeConfig and appConfig.

This article will explain the purpose and differences between these two options and show you how to use them.

Check it out here: Configuration in Nuxt: runtimeConfig vs. appConfig

📜 Dynamically Updating my Landing Page with Nuxt Content

I recently spent some time updating the landing page for Clean Components Toolkit so that it will automatically update the outline as I update the course content itself.

In this article, I'll show you how it's done.

Check it out here: Dynamically Updating my Landing Page with Nuxt Content

📅 Upcoming Events

Here are some upcoming events you might be interested in. Let me know if I've missed any!

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

VueConf US 2025 — (May 13, 2025 to May 15, 2025)

Giving a talk here on component patterns! A great Vue conference, this year held in Tampa. Two days of conference talks, plus a day for workshops.

Check it out here

MadVue 2025 — (May 29, 2025)

It's time to get together in Madrid. Join for a full day of talks, activities, and networking with the Vue.js community and ecosystem.

Check it out here

💬 Principles of Programmer Productivity

"What one programmer can do in one month, two programmers can do in two months." — Fred Brooks

🧠 Spaced-repetition: Fine-grained Loading API in Nuxt

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.

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 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 0    set,        // Overwrite progress    finish,     // Finish and cleanup    clear       // Clean up all timers and reset  } = useLoadingIndicator({    duration: 1000,  // Defaults to 2000    throttle: 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.

🔗 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:

Unsubscribe

评论

此博客中的热门博文

🔥 (#155) A Vue podcast?

Scripting News: Monday, November 20, 2023