Mokkapps Logo

Vue Tip: Use Optional Chaining in Templates

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
February 19, 2022
1 Minuten Lesezeit
- Ansichten

It’s possible to use Optional Chaining in Vue 3 templates:

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Here’s a simple Vue component that uses the optional chaining operator:

  <p v-if="data?.user?.name">Name: {{ data?.user?.name }}</p>
  <p>Age: {{ data?.user?.age ?? 0 }} years old</p>

<script setup>
import { ref } from 'vue';

const data = ref({ user: { name: 'Michael' } });

The following Vue SFC playground shows the rendered output of this Vue component:

If you liked this tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github