🔥 (239) Dynamic Slot Names, Using two script blocks, and Custom Directives

Read this on my blog

Hey there!

I've got some great content for you this week.

Enjoy!

— Michael

Vue Tips Collection

Level up your Vue skills with bite-sized, actionable tips delivered daily:

  • 118 carefully crafted tips covering both Vue 2 and Vue 3
  • Complete coverage of both APIs with examples in Options API and Composition API
  • Daily email delivery of 3 tips for 3 months
  • Beautiful hardcover book professionally printed in Canada
  • Instant digital access so you can start learning right away
"Michael explains complex topics in a way that's straightforward for all levels of Vue.js developers." — Ximo Belda

Master Vue in 5 Minutes a Day →

🔥 Dynamic Slot Names

We can dynamically generate slots at runtime, giving us even more flexibility in how we write our components:

<!-- Child.vue -->  <template>    <div v-for="step in steps" :key="step.id">      <slot :name="step.name" />    </div>  </template>

Each of these slots works like any other named slot. This is how we would provide content to them:

<!-- Parent.vue -->  <template>    <Child :steps="steps">      <!-- Use a v-for on the template to provide content           to every single slot -->      <template v-for="step in steps" v-slot:[step.name]>        <!-- Slot content in here -->      </template>    </Child>  </template>

We pass all of our steps to the Child component so it can generate the slots. Then we use a dynamic directive argument v-slot:[step.name] inside a v-for to provide all of the slot content.

When might you need something like this?

I can imagine one use case for a complex form generated dynamically. Or a wizard with multiple steps, where each step is a unique component.

I'm sure there are more!

🔥 Using two script blocks

The script setup sugar in Vue 3 is a really nice feature, but did you know you can use it and a regular script block?

<script setup>    // Composition API    import { ref } from 'vue';    console.log('Setting up new component instance');    const count = ref(0);  </script>    <script>    // ...and the options API too!    export default {      name: 'DoubleScript',    };  </script>

This works because the script setup block is compiled into the component's setup() function.

There are a few reasons why you might want to do this:

  • Use the options API — not everything has an equivalent in the composition API, like inheritAttrs. For these you can also use defineOptions.
  • Run setup code one time — because setup() is run for every component, if you have code that should only be executed once, you can't include it in script setup. You can put it inside the regular script block, though.
  • Named exports — sometimes, it's nice to export multiple things from one file, but you can only do that with the regular script block.

Check out the docs for more info

🔥 Custom Directives

In script setup you can define a custom directive just by giving it a camelCase name that starts with v:

<script setup>  const vRedBackground = {    mounted: (el) => el.style.background = 'red',  }  </script>    <template>    <input v-red-background />  </template>

With the Options API:

export default {    setup() {      // ...    },    directives: {      redBackground: {        mounted: (el) => el.style.background = 'red',      },    },  }

Registering a directive globally:

const app = createApp({})    // make v-focus usable in all components  app.directive('redBackground', {    mounted: (el) => el.style.background = 'red',  })

And since a very common use case is to have the same logic for the mounted and updated hooks, we can supply a function instead of an object that will be run for both of them:

<script setup>  const vRedBackground = (el) => el.style.background = 'red';  </script>    <template>    <input v-red-background />  </template>

You can find more info on custom directives in the docs.

📜 Custom Error Pages in Nuxt

Custom error pages are a great way to give your users a better experience when something goes wrong.

In this article, we'll go over how to create them in Nuxt.

Check it out here: Custom Error Pages in Nuxt

📜 Prisma with Nuxt: 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: Getting Data with Prisma (4 of 5)

💬 Working

"The greatest performance improvement of all is when a system goes from not-working to working." — John Ousterhout

🧠 Spaced-repetition: Teleportation

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 get an element to render anywhere in the DOM with the teleport component in Vue 3:

<template>    <div>      <div>        <div>          <teleport to="body">            <footer>              This is the very last element on the page            </footer>          </teleport>        </div>      </div>    </div>  </template>

This will render the footer at the very end of the document body:

<html>    <head><!-- ... --></head>    <body>      <div>        <div>          <div>            <!-- Footer element was moved from here... -->          </div>        </div>      </div>      <!-- ...and placed here -->      <footer>This is the very last element on the page</footer>    </body>  </html>

This is very useful when the logic and state are in one place, but they should be rendered in a different location.

One typical example is a notification (sometimes called a toast).

We want to be able to display notifications from wherever inside of our app. But the notifications should be placed at the end of the DOM so they can appear on top of the page:

<!-- DogList.vue -->  <template>    <div>      <DogCard        v-if="dogs.length > 0"        v-for="dog in dogs"        :key="dog.id"        v-bind="dog"      />      <teleport to="#toasts">        <!-- Show an error notification if we have an error -->        <Toast          v-if="error"          message="Ah shoot! We couldn't load all the doggos"        >      </teleport>    </div>  </template>

Which will render this to the DOM:

<html>    <head><!-- ... --></head>    <body>      <div id="#app">        <!-- Where our Vue app is normally mounted -->      </div>      <div id="toasts">        <!-- All the notifications are rendered here,             which makes positioning them much easier -->      </div>    </body>  </html>

Here's the complete documentation: https://vuejs.org/api/built-in-components.html#teleport

🔗 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

评论

此博客中的热门博文

丁薛祥在“77国集团和中国”气候变化领导人峰会上的致辞(全文)

The magic of scoped slots in Vue ✨ (3/4)