0 day streak
javascript / intermediate
Snippet

Optimizing Lists with v-memo

v-memo is a performance directive that memoizes a sub-tree of the template. The sub-tree will only re-render if one of the values in the provided array changes. In large lists, this can drastically reduce the number of DOM updates.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<div v-for="item in list" :key="item.id" v-memo="[item.id === selectedId]">
<p :class="{ active: item.id === selectedId }">
{{ item.name }}
</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const list = ref([{ id: 1, name: 'Alpha' }, { id: 2, name: 'Beta' }]);
const selectedId = ref(1);
</script>
vue
Breakdown
1
v-memo="[item.id === selectedId]"
The element only updates if the result of this comparison changes.
2
:key="item.id"
Always required when using v-for to help Vue identify elements.