Vue.js 2.0 experiences delays when making changes to irrelevant data

Imagine you have an input field in Vue.JS with a v-model that binds to a String data property, and a long list of random numbers that are completely unrelated to the first String.

data: {
  input: "",
  randoms: []
}

<input type="text" v-model="input">
<p v-for="random in randoms" v-text="random"></p>

Combining both in the same Vue instance results in a significant slowdown when typing in the input field. It seems like Vue is reevaluating the DOM for each list entry after every input event, although they are not related at all.

https://jsfiddle.net/5jf3fmb8/2/

However, moving the v-for to a child component where randoms is bound to a prop eliminates this slowdown.

https://jsfiddle.net/j601cja8/1/

Is there a way to achieve the performance of the second example without using a child component?

Answer №1

Is there a method to achieve the performance of the second violin without utilizing a child-component?

Succinct response

No, there isn't.

Detailed response

Each time any dependency of the template changes in Vue, the render function for the entire component must be re-executed and the new virtualDOM compared against the previous one. It is not possible to selectively update specific parts of the template while skipping others. Hence, every time the input value changes, the entire virtualDOM undergoes a re-render process.

Given that your v-for loop generates a significant number of elements, this can lead to delays of several hundred milliseconds, noticeable especially when typing.

The recommended approach to optimize this is to extract the resource-intensive part of the template into its own component.

Although using v-model.lazy as Alex mentioned may offer some slight improvement, it does not address the core issue at hand.

Answer №2

To simplify and reduce the lag, simply switch from using v-model to v-model.lazy.

Upon combining both in Vue, there is a noticeable slowdown when typing in the input field. It seems like Vue is re-evaluating the DOM for each list entry after every input event, even though they are unrelated.

Interestingly, the OnceFor example still experiences performance issues despite no longer being reactive. Whether this behavior is intentional or not within Vue remains unclear to me.

const Example = {
  data() { return { input: "", randoms: [] } },
  created() { this.newRandoms() },
  methods: {
    newRandoms() { this.randoms = Array(50000).fill().map(() => Math.random()) }
  }
}

new Vue({
  el: "#vue-root",
  data(){ return {example: 'lazy-model'}},
  components: {
    LazyModel: {...Example, template: "#lazy-model"
    },
    OnceFor: {...Example, template: "#once-for"
    },
    InlineTemplate: {...Example, template: "#inline-template",
        components: {
          Welp: {
            props: ['randoms']
          }
        }
    }
  }
})
button,
input,
div {
  margin: 2px;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="vue-root">
  <span><button v-for="(component, name) in $options.components" @click="$set($data, 'example', name)">{{name}}</button></span>
  <component :is="example"></component>
</div>

<template id="lazy-model">
<div>
  <input type="text" v-model.lazy="input"><br>
  <input type="submit" value="Regenerate" @click="newRandoms">
  <p v-for="random of randoms" v-text="random"></p>
</div>
</template>

<template id="once-for">
<div>
  <input type="text" v-model="input"><br>
  <input type="submit" value="Regenerate" @click="newRandoms">
  <p v-for="random of randoms" v-text="random" v-once></p>
</div>
</template>

<template id="inline-template">
<div>
  <input type="text" v-model="input"><br>
  <input type="submit" value="Regenerate" @click="newRandoms">
  <welp :randoms="randoms" inline-template>
    <div>
      <p v-for="(random, index) of randoms" :key="index"> {{index}}: {{random}} </p>
    </div>
  </welp>
</div>
</template>

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

The effectiveness of the javascript widget is hindered by the absence of the meta viewport tag,

As I work on creating a widget to appear at the bottom of webpages, I've encountered a styling issue. The widget's display varies based on whether the webpage includes a specified meta viewport tag or not. <meta name="viewport" content="width ...

An effective method for creating responsive layouts for custom-shaped HTML elements in a board game

Can anyone guide me on aligning spaces responsively on a board in HTML using Angular 1.x? I've tried using vw/vh's and %s, but consistency breaks on different view sizes. Any straightforward suggestions to address this issue? Avoiding multiple c ...

Turn off keycloak in vuejs exclusively in the test environment for development purposes

In my VueJS project, I have the following configuration set up: let initOptions = { url: 'http://localhost:81/auth', realm: 'cmt', clientId: 'cmt_api', onLoad: 'login-required' } let keycloak = Keycloak(initOpti ...

The event.submit/return true in JS/jQuery is not functioning as expected

Could someone lend a hand? I'm struggling with a validation script that checks an email form for content and a valid email. It's functioning correctly, but it's not submitting the form even when everything is correct - it just removes the er ...

Step-by-step guide on filtering an array of objects using Vuejs and TypeScript

For this particular project, I am utilizing Vuejs Typescript with a data structure that looks like this: ["order": { "id":1, "created_at":"2019-12-06T10:22:17Z", "status":"open", ...

Confirm that the Time sequence is accurate using JavaScript Selenium

I am working with a list of time intervals that includes 'a day ago, 10 days ago, 3 months ago, and 6 months ago.' How can I verify that these dates are in ascending order using JavaScript and Selenium? I am unsure of how to approach this proble ...

Is it possible to optimize the Dojo build system to only compile Dojo when necessary?

Greetings. I've been assigned the challenging task of enhancing the efficiency of the Javascript build process in our application. The current setup involves using Dojo libraries and build system, which takes approximately 6 minutes for a complete bui ...

Updating parent data after filtering props in a child component: A comprehensive guide

After filtering the month in the child component, I am trying to update the data in my parent component. However, when I attempt to download excel data using vue-json-excel, the filtered month in the parent component refuses to update. I have experimented ...

Cover the <img ...> tag in HTML using JavaScript

I'm currently working on creating a simple game involving sliding ice-blocks. I ran into an issue while testing this JSFiddle and I'm looking to "hide" the image/button triggered by the line alert('Game starts!');. I attempted using sta ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Having difficulty in closing Sticky Notes with JavaScript

Sticky Notes My fiddle code showcases a functionality where clicking on a comment will make a sticky note appear. However, there seems to be an issue with the Close Button click event not being fired when clicked on the right-hand side of the note. I have ...

Express always correlates the HTTP path with the most recently configured route

Recently, I encountered a strange issue with my Express routes configuration. It seems that no matter which path I request from the server, only the callback for the "/admin" route is being invoked. To shed some light on how routes are set up in my main N ...

Is there a way to dynamically adjust the height of a DIV block?

I have a situation where I need the height of one div to automatically adjust based on changes in the height of another div. var height = jQuery('#leftcol').height(); height += 20; jQuery('.rightcol-botbg').height(height); Unfortun ...

problem with creating a django template script

Hello, I am currently working on a code that is responsible for executing various functions within the template. I have utilized scripts to verify these functions using if-else statements and for loops. However, I am encountering some errors during this pr ...

ReactJS - Travel Booking Platform with Advanced Date and Price Filtering

Currently, I am in the process of developing a project — a website similar to AirBnB or Booking.com for booking rooms. The backend is built on Java Spring, while the frontend uses ReactJs. Although most of the code runs smoothly, I'm encountering s ...

How can I create a slot component with a prop defined in the child component?

If I have three components called Alpha, Bravo, and Charlie. Here is how they are structured: Alpha.vue <template> <div class="alpha"> <bravo> <template slot="card"> <charlie></cha ...

Discovering the Vue app container div attribute

I am currently working on a Java app that generates pages server-side based on certain data, such as a publisher for a specific entity. I want to develop a reusable Vue component that can call an API method to request data about the entity that is being vi ...

Is MongoDB-Stitch's Populate Method the best choice or are there comparable options available?

I am dealing with two collections, which I will refer to as A and B. Collection A contains documents that store the ObjectId of another document in collection B. For example: {name: String, age: String, bObjectId: ObjectId} When querying for an item in c ...

What is the process for encrypting a string in JavaScript?

Is there a simple way to hash a string in JavaScript without having to create the hashing algorithm myself? Are there any reliable npm packages or built-in functions available for this task? If so, how can I utilize them to hash a string? For instance, if ...