Javascript is required
·
1 min read

Vue Tip: Simple Expressions in Templates

Vue Tip: Simple Expressions in Templates Image

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.

1<template>
2  <span>{{
3    fullName
4      .split(' ')
5      .map((word) => {
6        return word[0].toUpperCase() + word.slice(1)
7      })
8      .join(' ')
9  }}</span>
10</template>
1<template>
2  {{ normalizedFullName }}
3</template>

We have moved the complex expression to a computed property:

1<script setup>
2const props = defineProps({ fullName: String })
3
4const normalizedFullName = computed(() =>
5  props.fullName
6    .split(' ')
7    .map((word) => word[0].toUpperCase() + word.slice(1))
8    .join(' ')
9)
10</script>

This tip is taken from the official style guide.

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.