Troubleshooting Vue JS 2: Issues with Computed Props

I've been diving into Vue.js by following a YouTube channel, but the video was uploaded last year and I think it might not be working properly due to changes in VueJS itself. It would be really helpful if anyone could assist me with this.

Here is the codeio link: http://codepen.io/myrgato/pen/BWWxdQ

HTML

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c1c2d2f78599859985">[email protected]</a>"></script>
<div id="app">
  <button @click="increment">Increment</button>
  <p>Counter: {{counter}}</p>
  <p>Clicks: {{clicks}}</p>
</div>

JS

new Vue({
  el: '#app',
  data: {
    counter: 0,
    clicks: 0
  },
  methods: {
    increment(){
      this.clicks++;
    }
  },
  computed: {
    counter(){
      return this.clicks * 2; 
    }
  }
});

It's designed to calculate the number of clicks and then use a computed property to display a counter that is equal to clicks multiplied by two. However, for some reason, it's not functioning as expected.

Answer №1

A concise yet comprehensive answer:

It is important to avoid using the same name for both your 'data' variable and 'computed' in Vue.js.

Consider data and computed as belonging to the same category, therefore their names should not overlap.

Answer №2

Here is a effective solution. The key is to:

  • utilize a distinct name for the calculated property (in this case counter2)
  • and employ a lambda function with just one parameter (here x) instead of using this.

new Vue({
  el: '#app',
  data: {
    counter: 0,
    clicks: 0
  },
  methods: {
    increment() {
      this.clicks++;
    }
  },
  computed: {
    counter2: x => x.clicks * 2
  }
});
<script src="https://unpkg.com/@[email protected]"></script>
<div id="app">
  <button @click="increment">Increment</button>
  <p>Counter: {{counter2}}</p>
  <p>Clicks: {{clicks}}</p>
</div>

Answer №3

In order to investigate the reason behind a certain occurrence, I conducted two tests on jsFiddle:

sample A:

sample B

Upon examination, it was evident that in sample B, the sequence of execution is as follows:

  1. Data properties are added first.
  2. The created hook is executed.
  3. The computed property calculates the value of the counter.

In contrast, in sample A, step 3 does not occur.

A warning you may encounter in vue2.1.0 is :

Vue warn: existing instance property "haveTrigger" will be overwritten by a computed property with the same name.


Further research in the documentation revealed that this warning is no longer present in vue 2.2.2 due to improvement in handling props and computed properties:

Props and computed properties are now defined on a component's prototype instead of as self properties on each instance. This avoids many calls to Object.defineProperty and improves component initialization performance. This will only affect you if you rely on hasOwnProperty checks on props and computed properties, which should be extremely rare, but we are documenting it here to be explicit about the change.

Source

var fancyConstructor = function () {
  this.value = 5
}

var instance = new fancyConstructor()

fancyConstructor.prototype.value = 5000
fancyConstructor.prototype.someOtherValue = 5000

console.log(instance.value)
console.log(instance.someOtherValue)

Exploring individual components further reveals the presence of computed properties assigned to counter.

https://i.sstatic.net/4Ob65.png

The provided code snippet demonstrates what occurs when a property by the same name exists on both the object and the prototype.

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

Tips for parsing a multidimensional associative array transferred from PHP to AJAX using jQuery

I'm currently working on a website that retrieves user location information (such as name, latitude, longitude, address, etc.) from a database using an AJAX request with jQuery. I have successfully fetched all the results and stored them in associativ ...

Validation of Dates

Having trouble with a JavaScript function I wrote to validate a date selected from a calendar against the current date. The date format being displayed in the text box is "01-Oct-2010". Here's the function I created: function CheckDate() { var to ...

Eliminate any unnecessary line breaks within the text box

Is there a way to identify line breaks in a text area using Java script? If two consecutive blank lines are found, remove one of them. If there is only one line present, delete it as well. I'm currently only able to delete single lines. Can anyone he ...

Manipulating CSS rules using JavaScript/jQuery

My goal is to create a function that generates a grid based on table data. While the function itself seems to be working, I am encountering an issue where the classes applied are not resulting in any style changes. Below is a snippet of my function: $(doc ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

Having trouble with Vue Router at the root path ("/") while utilizing Quasar Server-Side Rendering (SSR)?

THE ISSUE AT HAND I have a Quasar CLI (Webpack) setup for my app, and everything runs smoothly in SPA mode. However, when I switch to SSR, an unexpected issue arises. The Vue Router redirect from path "/"" to "/index" does not function as expected. Instea ...

The Angular directive alters the scope, however, the template continues to display the unchanged value

I am working with a directive that looks like this: .directive('myDirective', function() { return { restrict: 'AE', replace: true, templateUrl: '/myDirective.html?v=' + window.buildNumber, ...

The scrolling event on the div is not triggering

I'm struggling with this piece of code: const listElm = document.querySelector('#infinite-list'); listElm.addEventListener('scroll', e => { if(listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) { th ...

Storing translations in localStorage on my website to avoid repeatedly loading them each time I revisit the page

Recently, I created a function that loads translations for my website using an ajax request. However, I am now considering optimizing my code so that these translations are saved in localStorage and loaded from there instead of making a request every time. ...

Triggering the jQuery `one()` event from multiple locations for the same element

On the second open of my modal, I am experiencing unexpected behavior where a .one() event is being triggered from a different location than expected. The first time I click on .modal-trigger, everything works fine. The same goes for clicking on .close-mo ...

Having issues with ASP.NET MVC AJAX PartialView not loading Telerik UI components

I am facing an issue with a PartialView that I update using AJAX. The HTML elements load correctly when updating the Div with AJAX, but the Telerik chart is not loading. The datasource in the chart does not call the Action method: .DataSource(ds => ds. ...

Is there a method in Express to verify which URL a post is being sent to?

At the moment, I am using express to proxy my session creation URL in the following manner: app.post('/sessions', (req, res) => { // Code goes here }) The code that is used for this proxy also needs to be applied to my /confirmation endpoi ...

Encountering a 'require is not defined' issue while trying to implement chartjs within a JavaScript script

I am new to using Node.js and JavaScript. Currently, I am working on integrating chartjs into my project. Below are the HTML and JavaScript files associated with my project: charts.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <hea ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

Unable to display Three.JS OBJ Model

I am facing an issue with loading a .obj model in Three.js. I created the model in Cinema 4D, exported it with a scale of 1 meter, and tried to load it using OBJLoader in Three.js. However, even though there are no errors, the model is not showing up. Wh ...

The fetch API is being restricted, however, AJAX and XHR are still operational

I made an API call to a URL shortener and encountered different responses using Fetch, JQuery, and XHR. Why is Fetch returning a 400 error while the other methods work smoothly? Even after trying mode: 'no-cors' and "crossDomain": true in the re ...

The Angular application is experiencing issues following an update from version 11 to version 12

I recently updated my Angular project following these steps: npm cache clean --force npm uninstall @angular/cli@latest @angular/core@latest npm install -g @angular/cli@latest @angular/core@latest After completing the above steps, I proceeded to delete th ...

Guide on how to call a function in ascx code-behind using JavaScript within the framework of DotNetN

Currently, I am facing an issue with my module that involves submitting data to a SQL table in a database using code behind. My validation is done through javascript, and when a button is clicked and the data is valid, a div is displayed. However, the pr ...

Numerous column pictures that occupy the entire browser screen

I am looking to create a grid of clickable images that expand to cover the width of the browser window without any space on either side. Ideally, I would like each image to be 180x180px in size, but if it's easier they can resize based on the browser ...