How to use v-memo
April 27, 2022 ‐ 2 min read
Most of the Vue directives that are available have been in existence for a while. In Vue version 3.2 a new one was introduced however: v-memo
.
Vue directives are special HTML attributes that allow you to control how Vue renders your template.
The v-memo
directive allows you to memoize parts of your Vue template. Simply put, memoization is a technique to optimise programs for performance by letting functions return the same value without re-evaluating when the same inputs are given.
In a reactive frontend framework it is easy to imagine a use-case for this. Since Vue rerenders your components automatically when needed, there is a great chance that sometimes more code is executed than strictly necessary. This is where v-memo
comes in.
In its most basic form the v-memo
directive can be set on a HTML element and takes an array as its argument. When Vue rerenders your template, but every value in the array is the same as during the previous render then Vue skips that HTML element and all other elements inside.
See for example the following:
<template>
<header>
{{ currentPageTitle }}
<nav v-memo="[username, loggedIn]">
<span v-if="loggedIn"> {{ username }} </span>
<router-link v-else to="/login"> Login </router-link>
</nav>
</header>
</template>
Obviously, you want to update the page title in the above template whenever you change from page. However, the username or login link only require a rerender whenever either the username changes or when the user is logged in/out.
However useful, the above example won't save you much time. A more useful case would be when dealing with large lists for example; so combining v-memo
with v-for
. That would look as follows:
<template>
<ul>
<li v-for="item in items" :key="item.id" v-memo="[lastItem.id]">
{{ item.title }}
</li>
</ul>
</template>
For more information on v-memo
, you can read the excellent Vue docs.