vuejs mounted: Unable to assign a value to an undefined variable

When I try to run the function below upon mounted, I encounter an error:

"Cannot set the property 'days' of undefined"

Here is my code snippet:

 
       function getDays(date) {
           this.days = (new Date()).getTime() / (1000 * 24 * 60 * 60);
           return parseInt(this.days) - this.START_DAYS;
       }
     

I find it unhelpful that the error message doesn't specify the line causing the issue. My use of `this.days` instead of `let days` was due to a problem with VueJS.

Since I am still learning about VueJS and how it handles variables, any insights are appreciated.

Answer №1

Is this the way you set up your method? :

methods: {
    calculateDays(date) {
      this.days = new Date().getTime() / (1000 * 24 * 60 * 60);
      return parseInt(this.days) - this.START_DAYS;
    }
  },

Additionally, when invoking the method in mounted, remember to use: this.calculateDays()

You can refer to this codesandbox link for more clarity

Answer №2

To optimize your code, consider moving the getDays function to the methods section and then call it within the mounted lifecycle hook.

I noticed that you have included a date argument in the getDays function, but it is not being utilized within the method itself.

...
data() {
  return {
    days: ''
    START_DAYS: ''
  }
}
methods: {
  getDays(date) {
    // 'date' parameter seems unused here
    this.days = (new Date()).getTime() / (1000 * 24 * 60 * 60);
    return parseInt(this.days) - this.START_DAYS;
  }
},
mounted() {
  this.getDays()
}
...

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

Steps to resolve the error message 'npm ERR! Cannot read property 'startsWith' of null':

As I embark on creating my very first react-native app, I encountered a stumbling block while trying to set up the react-native command line interface following the instructions provided here. Every attempt I make to initialize the react-native command lin ...

I am unable to create a visual representation using the data obtained from the API

After utilizing Redux-Saga to fetch data from an API, I encountered difficulties accessing the updated state. This issue may stem from attempting to retrieve the data before it has been fully loaded into the redux state. //saga.js import axios from ' ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Utilize Element-UI to effectively close dropdown menus

In my Vue application with ElementUI, I have a drop down menu that needs to be explicitly closed after some logic is applied. The process is as follows: User loads the page, selects a name from the drop-down - the name value is saved in the database User ...

Each time the button is clicked, the settings and values will rotate, creating a new

I'm looking to create a button system that transitions from "unmarked" to "form" and updates the database with each click. I want users to be able to cycle through the buttons, triggering a post request via ajax to update the associated ID in the data ...

Ways to determine the total amount of days in a given month

As I create a countdown timer, the process involves determining the remaining days in a given month by subtracting the current date from the total number of days in that month. For instance, if there are 30 days in September and 8 days have already passe ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Using an AngularJS array with ng-repeat

As soon as a websocket message is received, the code below executes: connection.onmessage = function (eventInfo) { var onConnectionMessage = JSON.parse(eventInfo.data); if (onConnectionMessage.messageType === "newRequest") { getQuizRequests(); } } T ...

The webpack production build consistently displays the message "This site is running on the development build of React."

I have been attempting to utilize webpack-4 for generating a production build of my React project (not built with Create React App), but I am facing difficulties. The project is written in TypeScript and uses ts-loader, as well as React version 15.6.2. Be ...

After the click event, the variable in the Angular .ts file does not get refreshed

Great! I have a service in my .ts component that loops through an array of court names. Every time I click on a next or back arrow event, a counter is incremented starting at 0, where index 0 corresponds to field 1 and so on. The issue I'm facing is ...

Iterate through the elements in an array in order to generate new elements

Currently, I am in the process of comparing various popular javascript frameworks and I need to generate an HTML element for each object retrieved from an API. const frameworks = [ { name: "angular" }, { name: "ember" }, { name: "rea ...

Using XSL variables in JavaScript code

I've noticed that there have been similar questions asked, but none of the solutions seem to help in my case. So, I have this variable named 'var': <xsl:variable name="var"> val </xsl:variable> Now, I want to use it like thi ...

"Effortlessly attach and send multiple images via email using Dropzone in

I am encountering an issue with uploading multiple image files and sending them via email to customers. The ajax request is throwing an error call to a member function getclientoriginalname() on array when the uploadMultiple: true, option is added to dropz ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

create a sapper route using JSON data

Beginning with the official Sapper template, I am keen on implementing export default as recommended by eslint: export default function get(_, res) { res.writeHead(200, { 'Content-Type': 'application/json', }); res.end(conte ...

What could be causing my HTML elements to shift position based on varying screen sizes or zoom levels?

Does anyone else experience their HTML and CSS elements shifting around based on the screen size or zoom level? I have screenshots illustrating this issue. Here is how it currently appears And here is how it's supposed to look ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

Selenium Assistance: I'm encountering a scenario where on a webpage, two elements share the same Xpath, making it difficult to differentiate them based on even

At index [1], both elements are identified, but at index [2], nothing is identified. The key difference between the two is that one has display:none, and the other has display:block. However, their involvement in determining these fields is minimal due to ...

A common inquiry: how can one pinpoint a location within an irregular figure?

I have been studying Html5 Canvas for a few weeks now, and the challenge mentioned above has puzzled me for quite some time. An irregular shape could be a circle, rectangle, ellipse, polygon, or a path constructed by various lines and bezier curves... I ...

The AngularJs 2 framework encountered an issue with booting up after attempting to combine all TypeScript files into a single JavaScript file

I am currently utilizing Angular 2 with TypeScript (V-1.8) in my project setup. I have configured my tsconfig to output the code into a single .js file. This single.js file includes the necessary code to bootstrap the application, as the boot.ts file is al ...