Vue.js Developers

Helping web professionals up their skill and knowledge of Vue.js

Follow publication

Member-only story

Vue3 — why computed functions can make your code cleaner

Vue 3 is the latest version of the popular JavaScript framework for building web applications. One of the features that make Vue 3 stand out is its support for computed functions (Vue 2 also has this), which can help make your code a lot cleaner and more efficient.

To explain briefly, computed functions in Vue 3 are functions that are automatically re-evaluated whenever one of their dependencies changes. This allows you to declaratively specify complex logic in your templates, rather than having to manually update values or perform calculations in your code.

For example, consider a simple Vue 3 component that displays a list of items and a total count of those items:

<template>
<div>
<div v-if="loading">Loading...</div>
<div v-else>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<p>Total count: {{ totalCount }}</p>
</div>
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue';

interface Item {
name: string;
description: string;
}

export default defineComponent({
name: 'SomeComponentName',
setup() {
const items = ref<Item>([]);

const isLoading = computed(() => {
return items.value.length === 0;
});

const totalCount = computed(() => {
return items.value.length;
});

const fetchItems = async () => {
try {
const res = await axios.get('/api/items');
items.value = res.data as Item[];
} catch (e) {
throw new Error('an error happened' + e);
}
};

fetchItems();

return {
isLoading,
totalCount
};
}
});
</script>

In this example, the totalCount computed function is responsible for calculating the total number of items in the items array. The isLoading computed function returns a boolean value indicating whether the component is in a loading state or not, based on the length of the items array.

Notice how we are using the computed isLoadingto define if the application is loading. Usually, I see a lot of developers define a isLoading variable and set the variable isLoading to true when calling fetchItems, and then again set it to false once the API request is done. Doing a computed function for…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Vue.js Developers
Vue.js Developers

Published in Vue.js Developers

Helping web professionals up their skill and knowledge of Vue.js

Nicky Christensen
Nicky Christensen

Written by Nicky Christensen

Staff Software Engineer@Harness - A danish guy who speaks about frontend, tech & leadership - Follow & connect @ https://www.linkedin.com/in/dknickychristensen/

Responses (5)

Write a response