function() is not a valid function call;

I'm trying to make my function update the data shown on a Vue chart js whenever I click a button, but I keep running into the error message saying that "_vm.chartData is not a function". I followed the guide on using computed properties, but I must be missing something. Can someone assist me with this issue?

Here is the snippet of my code:

<template>
  <div>
  <Bar
    :chart-options="chartOptions"
    :chart-data="chartData"
  />
  <button v-on:click="chartData()">
    Change Data
</button>
  </div>
  
  
</template>

<script>
import { Bar } from 'vue-chartjs/legacy'

import {
  Chart as ChartJS,
  Title,
} from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChart',
  components: {
    Bar
  },
  data() {
    return {
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    }
  },
computed :{
  chartData() { 
        const updatedChartData = {
            labels: [
              'January',
              'February',
              
            ],
            datasets: [
              {
                data: [
                  this.getRandomInt(),
                  this.getRandomInt(),
                ]
              }
              ]
          };
        console.log(updatedChartData.datasets)
        return updatedChartData;
      },
  },
  methods:{
    
    getRandomInt() {
        return Math.floor(Math.random() * (50 - 5 + 1)) + 5
      }
  }
  
  
}
</script>

I would really appreciate any assistance with this. Thank you.

Answer №1

Vue simplifies the binding of templates to context, eliminating the need for this when working with variables and methods.

Consider the following code snippet (pun not intended): *Take note of the new variable chartDataValues

<template>
  <div>
    <Bar
      :chart-options="chartOptions"
      :chart-data="chartDataValues"
    />
    <button v-on:click="chartData">
      Change Data
    </button>
  </div>
</template>

<script>
import { Bar } from 'vue-chartjs/legacy'

import {
  Chart as ChartJS,
  Title,
} from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChart',
  components: {
    Bar
  },
  data() {
    return {
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      },
      chartDataValues: {}
    }
  },
  methods: {
    chartData() { 
      const updatedChartData = {
        labels: [ 'January', 'February' ],
        datasets: [{
          data: [ this.getRandomInt(), this.getRandomInt(), ]
        }]
      };
      console.log(updatedChartData.datasets)
      this.chartDataValues = updatedChartData;
    },

    getRandomInt() {
      return Math.floor(Math.random() * (50 - 5 + 1)) + 5
    }
  }
  
  
}
</script>

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 are some efficient ways to reduce the size of the vendor.js file generated by webpack

After running Google LightHouse on my development site, I received a warning advising to "Remove unused JavaScript". The site is built using Vue.js and webpack. It seems that the vendor.js file is being generated from the node_modules directory. I am wond ...

Exploring the Angular framework: Combining form requirements and controllers in directives' link functions

In my coding journey, I have developed a powerful directive known as formNavHandler. This directive plays a crucial role in handling dirty checking and smooth navigation between different pages. The functionality of formNavHandler heavily relies on the exp ...

Is there a way to make a sass file universally accessible without having to import it into every file and causing an increase in bundle size?

Question How can I efficiently import variables.scss globally without the need to duplicate them in every file and reference them in my build instead of importing? Setup I am using Vue2 with laravel-mix, where I have imported index.scss in my main.js ...

Using BeautifulSoup to Retrieve JPEG from an Image Tag's Src Attribute

Struggling with scraping this webpage for personal use. I am having trouble extracting the thumbnails of each item on the page. Despite being able to see image tags containing the required .jpgs when using "inspect" to view the html DOM, I cannot find the ...

Transform buffer information into a visual representation

How can I convert the buffer data into an image so that when I loop through the results and render it in the img src, the user will be able to see the image? I am currently using ejs for rendering. <span> <img class="user-with-avat ...

Exploring Ways to Retrieve Depth Information within three.js

I have come across shaders that can dynamically create outlines around edges based on the difference in depth of pixels. This means that pixels with less depth compared to their adjacent pixels might have a thinner outline or none at all. Examples of such ...

What causes the state hook in react to alter every single property within the object?

I have a list of team members and each member is associated with the same set of applications. I created 2 classes to link each member with their respective applications, resulting in a comprehensive list of all members and applications. This list was init ...

I am encountering the ERR_STREAM_WRITE_AFTER_END error in my Node.js API. Does anyone know how to resolve this problem?

When I try to upload a file using the API from the UI, I encounter the following issue. I am interacting with a Node.js API from React.js and then making calls to a public API from the Node.js server. https://i.stack.imgur.com/2th8H.png Node version: 10. ...

What is the process for applying the source from an object while utilizing video-js?

I've been struggling to use a video player for streaming m3u8 videos. The code below works, but I want to dynamically set the source using an object. <video id="my-video" class="video-js" auto ...

Optimizing the performance of J2EE web applications

I am currently working on enhancing the performance of my web application. The application is java-based and is hosted on an Amazon cloud server with JBoss and Apache. One particular page in the application is experiencing a slow loading time of 13-14 sec ...

What is causing the unexpected behavior of deferred.resolve in the q manual?

I can't seem to grasp this concept and it might be a silly question. Let's analyze the code snippet below: function throwError() { throw Error("can't touch this."); } var def = q.defer(); def.promise.then( function() { co ...

Matching nodes to selectors is a breeze with Angular JS and jqLite

Currently, I am in the process of integrating a few jQuery functions into jqLite to avoid loading the entire jQuery library when working with my angular applications. Following the approach outlined by Ben Nadel in his insightful article. However, I have ...

Toggle the visibility of an element using a checkbox in JavaScript

In my scenario, there are 8 checkboxes where only one is checked by default. If you click on the unchecked checkboxes twice, the table linked to them will hide. Ideally, I want the unchecked checkboxes to be hidden by default and the checked one to be sh ...

What could be causing an issue with CORS in ExpressJS in one scenario but not in another?

I am currently in the process of setting up a database and connecting it to various routes. Interestingly, I have been successful with one route ('register') but encountering issues with another ('login'). Whenever I attempt to run the ...

After applying styling, the modal close button refuses to be clicked

I'm currently facing an issue where I am trying to enhance a modal window with a close button, but encounter problems once styling is applied. The unique aspect of this problem arises from the fact that the close button is not directly in the page HTM ...

Performing an Ajax request using MooTools when my button is clicked

After clicking a button, I want to initiate an ajax call. There are more than 14 buttons on my site that make ajax requests to fetch elements from various parts of the site. Button, Button1, Button2, Button3 | | | load content | | ...

Find a way to avoid Google's site-blocking measures

Currently developing a website. I am looking into restricting access to only logged-in users on the site. How can I parse the pages in a way that Google does not block the site? ...

In order to add value, it is necessary to insert it into the text box in HTML without using the "on

example <input type="text" id="txt1" onChange="calculateTotal();" /> <input type="text" id="txt2" onChange="calculateTotal();" /> <input type="text" id="txt3" onChange="updateValue();" readonly/> <input type="text" id="txt4" onChange= ...

Disable touch interactions on the body, only allow pinch-zoom on specific elements

I have been attempting to implement the following code: body { touch-action: none; } .left-side { touch-action: pinch-zoom; } <div class="left-side"><img src="image.jpg" /></div> The touch-action: none is functioning properly, but ...

Transmitting JSON data object

Sending a JSON Object to JSP Page After following the provided link, I discovered that one of the answers suggests creating a JSON object using the following constructor: JSONObject jsonObj=new JSONObject(String_to_Be_Parsed); Upon downloading the JSON ...