Javascript is required
Mokkapps LogoMichael Hoffmann

Vue Tip: Simple Expressions in Templates

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Dec 10, 2021
1 min read
|
117 views
Template
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.

Bad
<template>  <span>{{    fullName      .split(' ')      .map((word) => {        return word[0].toUpperCase() + word.slice(1)      })      .join(' ')  }}</span></template>
Good
<template>  {{ normalizedFullName }}</template>

We have moved the complex expression to a computed property:

<script setup>const props = defineProps({ fullName: String })const normalizedFullName = computed(() =>  props.fullName    .split(' ')    .map((word) => word[0].toUpperCase() + word.slice(1))    .join(' '))</script>

This tip is taken from the official style guide.


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