JAVASCRIPT
Optimize List Rendering with Vue 3's `v-memo` Directive
Boost performance of large, complex lists in Vue 3 by using the `v-memo` directive to prevent unnecessary re-renders of static or unchanging content blocks within `v-for` loops.
// MyListComponent.vue
<template>
<div>
<h1>Product List ({{ products.length }})</h1>
<button @click="addProduct">Add Product</button>
<button @click="changeProductPrice(1)">Change Product 2 Price</button>
<button @click="toggleMemo">Toggle v-memo (currently: {{ useMemo ? 'On' : 'Off' }})</button>
<div v-for="product in products" :key="product.id">
<!-- Only re-render this block if product.price changes,
when v-memo is active and its dependencies change -->
<div v-if="useMemo" v-memo="[product.price]" class="product-item">
<h3>{{ product.name }}</h3>
<p>Price: ${{ product.price }}</p>
<small>Memoized content</small>
<hr>
</div>
<!-- Non-memoized version for comparison -->
<div v-else class="product-item">
<h3>{{ product.name }}</h3>
<p>Price: ${{ product.price }}</p>
<small>Non-memoized content</small>
<hr>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const products = ref([
{ id: 1, name: 'Laptop', price: 1200 },
{ id: 2, name: 'Mouse', price: 25 },
{ id: 3, name: 'Keyboard', price: 75 },
]);
const nextId = ref(4);
const addProduct = () => {
products.value.push({
id: nextId.value++,
name: `New Item ${nextId.value}`,
price: Math.floor(Math.random() * 100) + 10,
});
};
const changeProductPrice = (index) => {
if (products.value[index]) {
products.value[index].price = products.value[index].price + 10;
}
};
const useMemo = ref(true);
const toggleMemo = () => {
useMemo.value = !useMemo.value;
};
</script>
<style>
.product-item {
padding: 10px;
margin-bottom: 5px;
border: 1px solid #eee;
background-color: #f9f9f9;
}
</style>
How it works: The `v-memo` directive in Vue 3 allows you to skip re-rendering a template part if its dependencies haven't changed. In this example, the `v-for` loop renders a list of products. The `v-memo="[product.price]"` directive on the product item `div` means that this specific `div` will only be re-rendered if `product.price` changes. If other properties of `product` (like `name`) change, or if the `products` array itself is modified (e.g., adding a new product), `v-memo` prevents the re-rendering of *unchanged* memoized items, leading to performance improvements for large, complex lists with stable content.