Vue recalculate computed value only when result changes

Let's dive into a simplified version of the problem at hand:

export default {
    data () {
        return {
            i_change_alot: 0,
        };
    },
    mounted() {
        setInterval(() => {
            this.i_change_alot = Math.random();
        }, 10);
    },
    computed: {
        someComputedValue() {
            this.i_change_alot;
            
            return 'a';
        }
    }
}

I have created a property called i_change_alot which changes to a random value every 10 milliseconds, making it highly reactive and causing the computed property to be triggered.

Simply by referencing this.i_change_alot, I am able to trigger a dependency (for illustrative purposes), but the end result of the computed property remains constant.

This setup leads to the computed property someComputedValue being updated every 10 ms, subsequently triggering a rerender of the view.

How can we adjust this so that someComputedValue only updates when the value/outcome changes?

(The original issue pertains to displaying dynamically updating relative dates such as "1 second ago", "2 seconds ago," etc. However, once it reaches "30 minutes ago" and beyond, the string representation does not change for a full minute, yet continues to rerender every 10 ms due to the dependent date property).

As per https://github.com/vuejs/vue/issues/11399, one solution could involve structuring a watcher, although this approach may seem counterintuitive.

Answer №1

How does Vue handle computed values that remain unchanged?

Vue triggers the re-calculation of computed values whenever their dependencies change, as it cannot predict if the final result will remain the same without re-calculating. This means that even if the value of a computed variable remains unchanged, Vue will still update it.

One common misconception is that Vue caches computed variables based on their actual value, but in reality, it caches them based on the state of their dependencies.

Preventing excessive re-renders

To prevent unnecessary re-rendering, you can either use a watcher or encapsulate the template using the computed value within a separate component.

How does wrapping into another component help?

By wrapping the frequently updated variable in a separate component, Vue treats the template as a render function, recalculating it only when its dependencies change. This optimizes performance by avoiding re-rendering the entire large component every time there is a change.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing events in FullCalendar 5 using Vue.js's refetchEvents

I am currently integrating FullCalendar with Vue.js. My goal is to reload the events when the refreshCal() function is triggered, thereby rendering the calendar on the screen using refetchEvents. I have two main components: The Calendar: here is the code ...

Showcase JSON data within a designated div

As someone new to HTML, JavaScript and Vue, I'm unsure if my issue is specific to Vue or can be resolved with some JavaScript magic. I have a Node.js based service with a UI built in Vue.js. The page content is generated from a markdown editor which ...

Learn how to showcase a predetermined option in an HTML select element using Vue.js and Minimalect

I am currently utilizing Vue.js along with the Mininmalect HTML select plugin to showcase a list of countries by their names and values, where the value represents the 2 digit country code. Successfully, I have managed to implement the plugin for selectin ...

Issue with TypeScript in Vue3: Unable to access computed property from another computed property

In my Vue3 project with TypeScript, I am encountering an issue where I am unable to access the properties of the returned JavaScript object from one computed property in another computed property using dot notation or named indexing. For instance, when tr ...

retrieveSourceData(), postmodification of Handsontable with Vue

How can I use getSourceData() after a change event in Vue? I need to access the instance of Handsontable, but I'm not sure how to do that in Vue. Essentially, I need to retrieve all rows that have been edited. For example: const my_instance = this.$ ...

Utilizing Dynamic Image Sources in Vue.js with the Help of APIs

Can someone help me figure out how to solve this issue? I have an API that returns a base64 image, and I want to load this image on my site. Any suggestions on where or how I should implement my function? This is the API call located in the methods: metho ...

Vetur is experiencing issues with template functionality, such as not properly checking data and methods

I have incorporated the vetur extension into my Visual Studio Code for a Vue project using TypeScript. I recently discovered that vetur has the capability to perform type checks within the template tag for props, methods, and even variables. However, in ...

What is the reason for not being able to use a fixed number instead of referring to this.item.number?

<template> <Page> <ActionBar title="item" /> <ScrollView> <StackLayout> <Label textWrap="true" v-for="n in times" :text="n" /> </StackLayout> < ...

Implement VueJS functionality to prevent form submission upon submission and instead submit the form upon keyup

My form has the following structure: <form id="myForm" action="/searchuser" method="POST" @submit.prevent="onSubmit(inputValue)"> <div class="field"> <label class="label">Name</label> <div class="control"> ...

Vue3 project encountering issues with Typescript integration

When I created a new application using Vue CLI (Vue3, Babel, Typescript), I encountered an issue where the 'config' object on the main app object returned from the createApp function was not accessible. In VS Code, I could see the Typescript &ap ...

The Vue3 property 'x' is not recognized on type 'Function' as a global property

I have encountered a strange issue with my Quasar app. I am attempting to define a global variable that consists of metadata about the application in an object format. Despite successfully compiling the app and displaying the correct information on the HTM ...

Adding a CSS file in nuxt.js allows you to easily customize

I recently set up a new Nuxt project by using the command: vue init nuxt/starter <project-name> After creating my project, I made changes to the nuxt.config.js file by including the following code: css: [ { src: '~assets/css/style.css& ...

Avoid re-rendering the page in Nuxt when adjusting dynamic parameters

My page has two dynamic parameters that trigger the fetch method to run again when the URL params are changed. I want to avoid this behavior. Fetch Method: async fetch() { await this.getFlightResult(); } Get Result Method: async getResult() { th ...

Preserve chosen input values while toggling between two components in VUEJS

I currently have two components imported into my app.vue: <script> import Leaderboard from "./components/Comp1.vue"; import Search from "./components/Comp2.vue"; export default { name: "App", components: { Comp1, ...

Obtaining the user's IP address using Vue.js

Just started venturing into the world of Vue.js and I'm looking to retrieve a user's IP address within Vue.js. Prior to this, I was using req.ip inside my API, but unfortunately it always returned the IP address of the Vue.js server instead. I ...

Is there a way for a Vue component to interact with a button or checkbox in order to dynamically update tooltip content and button style using a function?

Is it possible for a Vue component to trigger button clicks or checkbox checks in order to update tooltip text and button color using a function? Despite the presence of a handle() function in the code provided, these changes are not currently taking effec ...

Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here. This is the code snippet from my A ...

Vue.js optimized for search engines

Is there a simple method to optimize an existing Vue app for SEO and ensure that all header meta-tags are search engine-friendly? I have explored NUXT, but the thought of having to reconstruct the entire app is daunting. Additionally, I am not particularl ...

Encountering NPM install gyp errors in VSCode indicating that gyp is searching for Visual Studio

Running npm install on a local project has been quite challenging for me, as I keep encountering errors every time I try. Fortunately, some valuable information I found related to gyp and Python helped me make some progress. However, I'm currently fac ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...