·
0 min read

Vue Tip: Use Optional Chaining in Templates

Vue Tip: Use Optional Chaining in Templates Image

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 checking that each reference in the chain is valid.

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

1<template>
2  <p v-if="data?.user?.name">Name: {{ data?.user?.name }}</p>
3  <p>Age: {{ data?.user?.age ?? 0 }} years old</p>
4</template>
5
6<script setup>
7import { ref } from 'vue'
8
9const data = ref({ user: { name: 'Michael' } })
10</script>

This Vue SFC playground shows the rendered output of this Vue component.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.