Each Vue.js component is intricately connected to one another, synergistically intertw

The behavior I expected from the component was for each one to be independent and display separate counters. However, it seems that this is not the case...

Below is the HTML structure:

<div id="app">
  <counter> </counter>
  <counter> </counter>
</div>

And here is the JavaScript code:

Vue.component('counter',{
  template: '<div>{{count}}</div>',
  data(){
    return {
     count:0
    }
  },
  created: function() {
    self = this;
    setInterval(function() {
    self.count +=1;
  }, 1000);
}
 })


 vm = new Vue({
  el: "#app",
 });

In addition, when using just one component, the counter increments by 1 as expected. However, when adding a second component, the first one stays at 0 and the second one increments by 2.

Answer №1

Without explicitly declaring self, the JavaScript interpreter will search for it as a property of the window object (as seen in window.self). Consequently, both instances of the component will access the same self property within the window object.

To avoid this behavior, consider defining self using either const or let:

let self = this;

Alternatively, you can utilize an arrow function to automatically bind the correct context:

setInterval(() => {
  this.counter += 1;
}, 1000);

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

What is the best way to insert CSS code into a custom Vue directive file?

I need a solution that applies a gradient background to the parent div in case an image fails to load. I've attempted to create a directive for this purpose: export default { bind(el: any, binding: any) { try { ..... ...

"Utilizing SharePoint's JSOM to retrieve taxonomy in a recursive manner

I am facing an issue with retrieving a tree of terms recursively from a term group using JSOM / JavaScript. The challenge lies in the fact that all values are being fetched recursively, but the order is completely incorrect. function recurseTerms(curre ...

Having trouble modifying the fields in the formArray

https://i.sstatic.net/B4uTq.pngWorking with reactive forms, I have a UI feature that displays radioButton options which, when selected, reveals details about the chosen value within the form. Once a button is selected, the form fetches data from the backen ...

Display real-time information in angular material table segment by segment

I need to incorporate service data into an Angular mat table with specific conditions as outlined below: If the difference between the start date and end date is less than 21 days, display 'dd/mm' between the 'start_date' and 'end ...

What is the reason behind this code's ability to detect vowels as well as other

I'm currently working on debugging a specific portion of code for my class. I'm having trouble understanding why this JavaScript code is counting all letters instead of just vowels. var text, i, sLength, myChar; var count; var text = prompt("Ple ...

Navigating Vue 3's slot attributes: A step-by-step guide

Currently, I am facing an issue with a Vue component named MediaVisual. This component contains a slot. The problem arises when attempting to retrieve the src attribute of the slot element that is passed in. Surprisingly, this.$slots.default shows up as u ...

The Angular route functions flawlessly in the development environment, but encounters issues when deployed to

I have a project built with Angular 2, During development on localhost, everything runs smoothly. However, once I build a production version using (npm run build: prod) and navigate to the route on the server, I encounter a 404 error indicating that the r ...

The functionality of an Ajax call is limited to a single use, regardless of using

For the past couple of weeks, I've been struggling to get my Ajax call to function more than once. As a self-taught individual, I've been trying my best to troubleshoot this issue on my own, but it's really getting to me. Some others facing ...

The appearance of HTML varies depending on the type of mobile device being used

My email template is having display variations on different mobile devices, with the textbox sometimes centered instead of left aligned as intended. Any suggestions on what might be causing this issue and how to resolve it? Desired Display on All Devices ...

Building a multilingual website using AngularJS UI-Router

I am currently working on developing a multilingual website using AngularJS. While providing translations in templates seems straightforward, I am facing challenges when it comes to implementing proper multilingual routes using UI-Router. Unfortunately, I ...

Determining if data from two separate lists in Vue.js matches in order to display in the template

I need to compare two sets of data - one fetched from the server and the other being default data. Data retrieved from the server: [ { "id": 7, "day": "14 April 2017", "time_list": [ { "id": 25, "time": "11:00 AM", ...

Guide to activating a watcher once the page finishes loading

One of my challenges involves a watcher calling a method: watch: { 'list.items' (n, o) { this.doSomething() } } Every time the page loads, new values are added to list.items like this: methods: { fetchLists(){ axios.get('/ ...

Is it possible to retrieve the vertices array from a QuickHull instance in three.js?

I'm currently working on generating a geometry using QuickHull from a THREE Mesh. However, it seems that the QuickHull object only contains information pertaining to the Faces of the mesh. Does anyone know if there is a way to access the vertex infor ...

Tips for successfully retrieving a variable from a function triggered by onreadystatechange=function()

Combining the ajax technique with php, I'm looking to extract the return variable from the function called by onreadystatechange. A java function triggers a call to a php script upon submission, which then validates certain data in the database and r ...

Exploring methods to trace the factory's property that is receiving updates from another factory within AngularJS

Hey there, I'm new to Angularjs and I have a bunch of factories in my application. The situation is, let's say we have obj1 in factoryA. Whenever I console.log(obj1), it displays numerous properties associated with it. This object is being update ...

The export of "asyncDataDefaults" cannot be found in the "virtual:nuxt" module

When trying to run my Vue project on Netlify and executing the 'pnpm run build' command, I encounter the following error: ERROR "asyncDataDefaults" is not exported by "virtual:nuxt:C:/Users/VasilisKaramanis/Desktop/cv_vue_copy/.nuxt/nuxt.config.m ...

Cease animation if the page has already reached its destination

In my current setup, I am using a JavaScript code snippet to navigate users to the specific location of the information they click on in a side navigation menu. However, one issue that arises is if they first click on one item and then another quickly, t ...

How can Vue.js be used to generate an href link from Vue data response and transmit it to the following request?

After researching on Google for a solution to my problem, I came across this answer. However, it did not work in my case. Let me provide an example from the project I am currently working on, which is developed in Laravel. The following code snippet is fr ...

What is the best way to show a specific element within a list item when clicked using AngularJS?

Is there a way to display an iframe element inside an li element on ng-click, but only for the specific one that was clicked? Additionally, how can all iframes be hidden using AngularJs? <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6. ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...