Mokkapps Logo

Vue Tip: Simple Expressions in Templates

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
December 10, 2021
1 Minuten Lesezeit
- Ansichten

Your Vue component templates should only include simple expressions as they make your template more declarative.

If you have more complex expressions in your Vue.js component templates you should refactor them into computed properties or methods. This allows us to reuse the code.

<!-- In a template -->
  fullName.split(' ').map((word) => {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')

<!-- In a template -->
<span>{{ normalizedFullName }}</span>

We have moved the complex expression to a computed property:

<script setup>
const props = defineProps({ fullName: String });

const normalizedFullName = computed(() =>
    .split(' ')
    .map((word) => word[0].toUpperCase() + word.slice(1))
    .join(' ')

This tip is taken from the official style guide.

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