Vue users are experiencing issues with the functionality of the Chart js plugin annotation

I've been attempting to include a horizontal line in my Chart.js using the annotations plugin, but it's not cooperating.

My Chart.js version is 2.9.4, so I had to install it with the command: npm install [email protected] --save

After installation, when I tried to register it using Chart.register(annotationPlugin), I received the error:

TypeError: chart_js__WEBPACK_IMPORTED_MODULE_10__.Chart.register is not a function

After some online research, I discovered that I could use:

Chart.plugins.register(AnnotationPlugin)
and that seemed to resolve the issue.

Below is my chart configuration:

import BarChart from '../Charts/BarChart'
import DetailsComponent from './Reusable/Details'
import AnnotationPlugin from 'chartjs-plugin-annotation';
import Chart from 'chart.js';

export default {
  data() {
    return {
      aud2Chart: {
    chartdata: {
      labels: [],
      datasets: [
        {
          label: "Valor da nota",
          fill: false,
          tension: false,
          pointRadius: 5,
          pointHitRadius: 10,
          pointHoverRadius: 10,
          backgroundColor: "#556aff",
          data: [],
          pointBackgroundColor: []
        },
      ],
    },  
    options: {
    annotation: {
        annotations: [{
            id: 'a-line-1',
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y-axis-0',
            value: '15000',
            borderColor: 'red',
            borderWidth: 2,
        }]
    },
      legend: {
        onClick: null
      },
      tooltips: {
        mode: 'index',
        callbacks: {
          label(vars){
            let float = parseFloat(vars.value).toFixed(2)
            let parts = float.toString().split(".")
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ")
            let formatted = parts.join(".").replace('.', ',')

            if(vars.datasetIndex == 0){  
              return 'Valor total da nota fiscal: ' + formatted
              } else { 
              return 'Média deste momento: ' + formatted
            }
          }
        }
      },
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
            },
          },
        ],
      },
      responsive: true,
      maintainAspectRatio: false,
    },
  },
...

The graph data is not included in the code as it is fetched from the API.

No errors are showing up in the console.

I attempted one solution I found, which involved wrapping the annotation object inside a plugin{} object, but it didn't work.

For reference, I'm using vue-chartjs as well, and I'm importing this component to display the graph:

<script>
import { Bar } from "vue-chartjs";

export default {
  extends: Bar,
  props: ["chartdata", "options"],
  mounted() {
    this.renderChart(this.chartdata, this.options);
  },
};
</script>

Here are some of my settings:

Chart.js version: 2.9.4 Annotations plugin version: 0.5.7 Vue-chartjs version: 3.5.1

Thank you for your help!

Answer №1

When working with v2, make sure to register plugins properly and avoid using v3 syntax. Here is the correct way to register plugins in V2:

import AnnotationPlugin from 'chartjs-plugin-annotation';

Chart.plugins.register(AnnotationPlugin)

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

Using SVG in a Vue standalone script without the need for a build step is easy with the

When I attempt to utilize Vue as a standalone script in an HTML file, my inline svg icons are rendered as solid filled squares instead of their intended shapes. This issue persists when using both Vue 2 and Vue 3 as standalone scripts. Although there are ...

I am currently utilizing react-admin, however, I am encountering an issue with the heavy build causing errors

Currently, I am working on developing the frontend using react-admin. Initially, I intended to utilize NextJS and found a helpful reference article. Reference: When attempting to run next dev, everything worked smoothly without any errors. However, when ...

The jQuery ajax function is not properly displaying or hiding the loader div

While attempting to call PHP code using a jQuery AJAX function, I encountered an issue where I wanted to display a loader div while the request was being sent and then hide the div once the request was complete. To simulate this scenario, I deliberately de ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

Control the line height in DataTables

Is there a way to adjust the line height for a tr using either DataTables settings or CSS? I've attempted different methods, but nothing seems to change the line-height. https://i.sstatic.net/GwFaD.png Table CSS ...

Flask fails to recognize JSON data when transmitted from Nodejs

I am encountering an issue when trying to send JSON data from Node to Flask. I am having trouble reading the data in Flask as expected. Despite attempting to print request.data in Flask, no output is being displayed. Additionally, when I tried printing req ...

outputting javascript within php

I'm struggling to extract the data returned by AJAX after a successful call. Instead of just getting the words printed by my JavaScript code, I end up with the entire script that is echoed in the PHP file. What I really need are only the words outputt ...

AngularJS closes when clicked outside

I've been attempting to add a close on outside click functionality to my code, similar to this example: http://plnkr.co/edit/ybYmHtFavHnN1oD8vsuw?p=preview However, I seem to be overlooking something as it's not working in my implementation. HT ...

What are strategies for handling intricate state logic within my Vue.js checkbox component?

I'm facing a few challenges as I dive into learning Vue.js for just one week. Keep in mind that this example is actually nested within a parent component called <question>, but for the sake of simplicity, I've streamlined the code for this ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

Module.exports causing keyword errors in eslint

Encountering some unusual errors from eslint CI regarding my jest.config.js file. 1:1 error Rule 'no-empty-label' has been replaced by: no-labels no-empty-label 1:1 error Rule 'no-reserved-keys' has been replaced ...

Choose an option from a dropdown menu and assign it to a JavaScript variable

Is it possible to store the selected option from a dropdown list as a JavaScript variable, even when new Ajax content is loaded on the page? Below is a simple form code example: <form name="searchLocations" method="POST"> <select name="l ...

Is there a way to eliminate the surplus 2 download icons from this Angular code when there are a total of 3 users?

Here is some HTML code snippet: <tr *ngFor="let user of users"> <td> <h6 class="font-medium">{{user.id}}</h6> </td> <td> <h ...

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...

ng-repeat hide all elements except the first one

Hello there! I'm currently working on rendering a form based on an API call. Using a couple of filters, I am able to hide all elements that have 'id' in the title and which equal 0. However, I do need to display the initial element Id. I tho ...

What is the best way to invoke a custom hook that returns a value within the useEffect hook?

I have a unique situation where I am using a custom hook that returns an object based on the parameter it receives. I now need to modify this behavior by recreating the object with updated parameters within the useEffect function. The challenge is that I c ...

Should I implement this practice when developing an AJAX website? Is it recommended to enable PHP code within .html files, or should I switch to using .php files instead?

Query: I am interested in executing PHP within HTML documents to include HTML using PHP include();. Question: Would it be more beneficial to change .php to .txt for my AJAX-loaded pages and switch my .html files to .php? This approach might resolve the ...

"Enhance your React application with react-router-dom by including parameters in the index URL while also

Here is the code I am currently using: <Router history={history}> <div> <Route exact path="/:id?" component={Container1} /> <Route path="/component2/ component={Container2} /> </div> </Router> When accessin ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

Stretching the Mantine Accordion Section

The Mantine accordion requires that its content be of type Accordion.Item, as indicated in the documentation for the children props. This means that even functions returning AccordionItem will not be recognized. Therefore, only AccordionItem(s) created in ...