Is Incrementing and Refreshing in Vue.js: a glitch or a capability?

I've been delving into vue.js to enhance my skills and encountered an interesting behavior that I can't quite figure out. The scenario involves incrementing and re-rendering a basic output like so:

<div id="app">
    <h1> Seconds : {{ number }}</h1>
    {{ update() }}
</div>

</body>

<script>
    new Vue({
        el: "#app",
        data: {
            number: 1
        },
        methods: {
            update() {
                setInterval(() => {
                    this.number++
                }, 1000)
            }
        }
    })

</script>

Everything appears to be working fine, except for the fact that instead of simply incrementing by 1...2...3...4...5..., the output doubles, displaying as 1...2...4...8...16...32...

Even when changing

this.number++

to

this.number = this.number + 1

The doubling effect persists. What am I overlooking here? Is this a bug or an unexpected feature?

Answer №1

Every time the component is rendered, the update function is being executed.

Since the rendering depends on the number variable, any change in the variable triggers a re-render of the component, causing the update function to be called again.

setInterval is used to repeatedly call a function or execute a code snippet. setInterval

This creates multiple timers that increment the number variable.

It is not recommended to call a function in the template. Instead, consider calling the update method in the created lifecycle hook, which is only called once.

Created

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    number: 1
  },
  created() {
    this.update();
  },
  methods: {
      update() {
          setInterval(() => {
              this.number++
          }, 1000)
      }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <h1> Seconds : {{ number }}</h1>
</div>

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

Saving numerical data from Firebase using Vue.js

I am currently using Firebase in combination with Vue.js. When saving data to the database, I execute the following command: saveEvent(){ db.collection('events').add({ title: this.title, content: this.content, start: this.start, ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

Unable to locate video identifier on ytdl

Lately, I have been working on developing a music bot for Discord. I have successfully managed to make it join and leave voice channels flawlessly, but playing music has proven to be quite challenging. For some reason, the play and playStream functions do ...

Unfortunately, the YouTube iframe Embed feature does not have the ability to adjust audio settings on an

I've been experimenting with the YouTube iframe API and created a simple set of player controls for the YouTube player using Flash CC HTML5 canvas. The controls include a play/pause button, a draggable video bar with buffering visualization, and a vol ...

Having trouble launching the Nuxt 3 development server because the module '@volar/typescript/lib/node/proxyCreateProgram' cannot be located

Whenever I attempt to execute npm run dev, the dev server initiates but encounters the following error: Cannot start nuxt: Cannot find module '@volar/typescript/lib/node/proxyCreateProgram Require stack: - node_modules\vite-plugin-checker&bsol ...

Guide for dynamically populating Jqgrid Dropdown depending on another dropdown's data选择如何根

On my screen, I have two dropdowns. One is a standard Razor dropdown and the other is a Jqgrid dropdown. The code for the Razor dropdown looks like this: <div class="col-md-4"> <label for="" class="control-label">Loan Currency</ ...

Incorporating unique components dynamically using a loop in React

As I delve deeper into learning React and experimenting with some basic concepts, I have encountered a seemingly straightforward issue that has left me stumped. Despite my best efforts to search for a solution online, I have come up empty-handed. The crux ...

What steps are needed to successfully enable the callback function within the addFilter method from @wordpress/hooks while customizing the tables in WooCommerce analytics reports?

I've been diving into customizing Analytics reports tables for clients on our WooCommerce platform. I followed a guide at this link, but encountered an issue with the JavaScript file. After adding the filter at the end of the file as instructed, noth ...

Enhance with Laravel combined with AngularJS

I've encountered some issues with the "edit" part while working on a Laravel + AngularJS CRUD application. An internal server error is being displayed, and I'm seeking assistance to understand its cause. Error "GET localhost/crudtcc/public/ap ...

Error: Unable to call dispatch method on this.$store object

I'm diving into Vue and hitting a wall with this error message. TypeError: this.$store.dipatch is not a function I've set up the store.js file and am attempting to call actions from within a vue file. I've scoured the internet for answers ...

Is it possible to utilize Vue 3's watch feature with primitive data types?

When I retrieve data, I want to toggle a boolean value to display the <Loading /> component. I prefer not to base my condition on array length. Therefore, I have opted for this approach. However, the <Loading /> component does not respond to ch ...

Firestore is not capable of preserving line breaks when storing text from text areas

I have encountered an issue where line breaks disappear when using a text area with Vue v-model and saving the data in a firestore collection. Is there a way to preserve the line breaks in the database? <div class="form-group"> <textarea v-m ...

The afQuickField in Meteor is unable to locate the function when using the onfocus feature

I'm currently working on implementing a dynamic help feature that changes when the focus shifts using Meteor AutoForms. It's similar to the "Similar Questions" box that appears when you ask a question here. However, I'm encountering an issue ...

AngularJS Controller managing the entry field

I am still learning AngularJS and attempting to retrieve user input from a text box to use for querying an endpoint and displaying the result in another text box. Here is a preview of the user interface: https://i.sstatic.net/zXCgQ.jpg Here is the HTML c ...

Angry Librarians Uncover Secret to Incrementing Variable in Angular.js

Check out my HTML snippet: <div ng-app='app'> <div ng-controller="MyController" ng-init="myVar=7"> {{myVar}} <span ng-init="myVar=myVar+5">{{myVar}},</span> <span ng-init="myVar=myVar+15">{{myVar}},</ ...

Get the PDF document via FTP by utilizing an XMLHttpRequest and a generic handler

Attempting to download a PDF file from an FTP server using a JQuery Ajax request. The reference used was found at . Below is the Jquery ajax call being made: $.ajax({ xhr: function () { var xhr = new window.XMLHtt ...

Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind: function fetchDesign (items) { items.map(item => item.classList.add('selected')) // additional code here } Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensu ...

The scoping of CSS in Vue becomes ineffective when the ExtractTextPlugin is utilized

Here is an example of Vue code that works perfectly in development: <template lang="pug"> .wrapper </template> <style lang="stylus" scoped> .wrapper min-height: 100vh display: flex justify-content: center align-items ...

What is the method for acquiring a dynamic segment in the router of a Next.js 13 application?

Currently in my project, I am using the new App Router in Next.js 13 and MongoDB as the DBMS to fetch data via API. When trying to retrieve all data from a collection, it is successful. However, fetching only one data results in failure. The error message ...