Vue.js - the value of this is not defined

<div class="content-chart">
 <chart :type="'line'" :data="lineData" :options="options"></chart>
</div>

In the template section above, a component is defined to render a chart using Chart.js. The script below handles the logic.

<script>
import Chart from 'vue-bulma-chartjs'
import { Tabs, TabPane } from 'vue-bulma-tabs'
export default {
  components: {
    Chart
  },
  data () {
    return {
      persondata: {},
    }
  },
  mounted () {
    let parameter = this.$route.params.id
    axios.get('/api' + parameter.toString()).then(response => {
     this.persondata = response.data
    })
  },
  computed: {
    lineData () {
      var sth = this.person.dates['date-values']
      return {
        labels: [9, 10, 11, 12, 13, 14, 15],
        datasets: [{
          data: sth,
          label: 'Speed',
        }]
      }
   }
}
</script>

As observed, this Vue component is used to display a chart on the page using Chart.js. However, an error occurs when attempting to access this.persondata.dates in the mounted() function, resulting in

"TypeError: this.persondata.dates is undefined"
. A potential solution involves initializing this.persondata with nested properties as shown below:

data () {
  return {
    persondata: {
      dates: {
        'date-values': []        
      }
    }
  }
}

Despite this, if the

response.data.dates['date-values']
is assigned to
this.persondata.dates['date-values']
and used in the dataset.data within the computed() function, the chart fails to render. This poses the question: What could be causing this issue?

Answer №1

Calculated properties are computed immediately: they are calculated prior to the completion of your Ajax request.

When persondata is only filled once the Ajax request is complete, the initial value of persondata is {} (as initialized in the data).

Simple solution: start with an empty dates object to prevent errors during computation (allowing enough time for the Ajax request to finish and update the computed property automatically):

  data () {
    return {
      persondata: {dates: {}}, // added empty dates property
    }
  },

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

Enable vertical scrolling on the second row of a table while keeping the first row fixed as the table header (CSS)

While embedding the Ace Editor in a Chrome popup window, I encountered a challenge. My goal was to keep the first row of text always visible at the top while allowing the rest of the Editor to fill the screen. However, there is an issue with a vertical scr ...

Result of utilizing Bootstrap Radio buttons

Looking at the HTML snippet below, I am trying to display two lines of radio buttons. However, when I click on a radio button in the first line and then proceed to click any radio button in the second line, the result of the radio button in the first line ...

Fixing "local storage not defined" issue in vue.js

While attempting to run test cases in vue.js, I encountered an error stating that local storage is not defined. Can anyone provide guidance on resolving this issue? [Login.spec.js] import Login from '../../src/Pages/Login.vue'; import{shallowMo ...

Exploring the debugger statement functionality within Vue 2's production code

How can I check if a user has devtools open in my Vue 2 webapp? I am using @vue/cli 5.0.8 with the default configuration for creating and building the app. I came across this code snippet that might work - const minimalUserResponseInMilliseconds = 100; co ...

Jquery is failing to handle multiple inputs

I am currently working on a system that can handle multiple Yes/No questions. However, every time I try to submit the form, I encounter an error in the console that I cannot identify, and no data is returned from the query. Previously, I used an Array to s ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

Avoiding the hashtag symbol in a serialized string

I have a serialized string that I am sending to the server, structured like this: counter=1&Id=4&type=2332&amount=3232&gstIncluded=3232&paymentMethod=2&notes=2332#fdsf&docId=0&ref=3232&isEdit=true The issue I am encoun ...

The novice image slideshow script in JavaScript is causing all images to disappear and generating errors

Trying to create a simple image slider that pulls information from various sources. CSS and HTML are set up properly, but adding the JavaScript logic causes all images to disappear. The console displays an error saying "Uncaught TypeError: Cannot read prop ...

How can I access all the connected "guilds/servers" on this Discord bot?

When I try to access client.guilds, I receive an unfamiliar object that I am struggling to interpret. Object: GuildManager { cacheType: [Function: Collection], cache: Collection(1) [Map] { '11111111111111111' => Guild { // Guil ...

How can we develop a NodeJS function that returns a query result using a callback method?

I'm currently working on verifying the proper operation of a database using mocha/chai in NodeJS. I am looking for a solution to run a SQL query and then validate its execution. The issue I'm facing is that when I reach the assertion, the result ...

Child component in VueJS has the ability to change the class of its parent button

I am currently working on a Navigation component that includes a button for toggling between dark mode and light mode. My goal is to change a specific class in the App.vue file when this button is clicked. However, I am facing difficulties in passing the d ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

How to prevent mouse click events in Three.js after interacting with an HTML overlay

Encountering an issue with Three.js: I have created my own HTML user interface as a simple overlay. However, I am facing a problem where the mouse click does not reset when I interact with elements on this overlay. Specifically, when I click on the "Came ...

Checkbox change cannot be initiated

Using jQuery version 1.8.3, I am attempting to trigger a state change for each checkbox. The following code works when placed inside a click event: $("#btn_off").click(function(){ $( "tr td input" ).each(function( index ) { if ($(this).is(":ch ...

Using MongoDB to restrict fields and slice the projection simultaneously

I have a User object with the following details: { "_id" : ObjectId("someId"), "name" : "Bob", "password" : "fakePassword", "follower" : [...], "following" : [..] } My goal is to paginate over the follower list using the slice projection operat ...

Formatting numbers as floating point values in AngularJS

I need a text box where users can enter an amount. The input should be restricted to numbers only, with no special characters or decimal points. I have managed this using custom filters. However, I also need the entered number to automatically display as ...

The authorization process for uploading data to Azure Data Lake Gen2

Currently, I am working on generating a Shared Access Signature (SAS) client-side within my Node.js application. The primary goal is to allow users to directly upload files to my Azure Data Lake Gen2 Blob Storage container without streaming them through th ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...