Displaying dynamic data with Vue.js and Chart.js

I am currently working on a VueJS code to display a bar-chart:

Vue.component('bar-chart', {
    extends: VueChartJs.Bar,
    data: function () {
        return {
            datacollection: {
                labels: ['MICROFINANZAS -SECTOR COMERCIO','MICROFINANZAS -SECTOR SERVICIOS'],
                datasets: [
                    {
                        label: 'Data One',
                        backgroundColor: '#f87979',
                        pointBackgroundColor: 'white',
                        borderWidth: 1,
                        pointBorderColor: '#249EBF',
                        data: [15000, 71700]
                    }
                ]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        },
                        gridLines: {
                            display: true
                        }
                    }],
                    xAxes: [{
                        ticks: {
                            beginAtZero: true
                        },
                        gridLines: {
                            display: false
                        }
                    }]
                },
                legend: {
                    display: false
                },
                tooltips: {
                    enabled: true,
                    mode: 'single',
                    callbacks: {
                        label: function (tooltipItems, data) {
                            return '$' + tooltipItems.yLabel;
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false,
                height: 200
            }
        }
    },
    mounted() {
        // this.chartData is created in the mixin
        this.renderChart(this.datacollection, this.options)
    }
})

Method in VueJS

var app = new Vue({
    el: '#grid',
    data: {
      columns: ['id', 'nombre'],
      objeto: "",
      searchQuery: "",
      dataChart: "",
      dataChart1: "",
    },
    created: function () {
        this.getDeudas();
    },
    methods: {        
            getDeudas: function () {
                this.$http.get(baseURL + "/Home/ConsultarDeudasHome").then(function (response) {
                    this.lista = response.data.data;
                    console.log(this.lista);
                    this.objeto = JSON.parse(this.lista);
                    console.log(this.objeto[1].original);
    
                    this.dataChart = [this.objeto[0].original, this.objeto[0].actual];
                    console.log(this.dataChart);
                    this.dataChart1 = [this.objeto[1].original, this.objeto[1].actual];
                });
            },
        },

This code show this bar chart: https://i.sstatic.net/hyh4S.png

However, I now need to dynamically replace two variables in my code:

labels: ['MICROFINANZAS -SECTOR COMERCIO','MICROFINANZAS -SECTOR SERVICIOS'],

data: [15000, 71700]

I intend to achieve this by using the information from the method getDeudas()

Can anyone guide me on how to implement this?

Answer №1

Here is my approach using props and watch:

Vue.use(VueTables.ClientTable);
Vue.component("bar-chart", {
    extends: VueChartJs.Bar,
    props: ["data", "options"],
    mounted() {
        this.renderLineChart();
    },
    computed: {
        chartData: function () {
            return this.data;
        }
    },
    methods: {
        renderLineChart: function () {
            this.renderChart(
                {
                    labels: ["Sector Retail", "Sector Technology"],
                    datasets: [
                        {
                            label: "Aggregate",
                            backgroundColor: "#f87979",
                            data: this.chartData
                        },
                    ],
                },
                { responsive: true, maintainAspectRatio: false }
            );
        }
    },
    watch: {
        data: function () {
            this.renderLineChart();
        }
    }
});



const baseURL = window.location.protocol + "//" + window.location.host;
var app = new Vue({
    el: '#grid',
    data: {
      columns: ['id', 'name'],
      object: "",
      chartData: "",
    },
    created: function () {
        this.getDebts();
    },
    methods: {        
        getDebts: function () {
            this.$http.get(baseURL + "/Home/GetDebtsHome").then(function (response) {
                this.list = response.data.info;
                this.object = JSON.parse(this.list);        
                this.chartData = [this.object[0].original, this.object[1].original];
            });
        },
    },
})

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

Experience seamless transitions with Material UI when toggling a single button click

When looking at the examples in the Material UI Transitions documentation, I noticed that there are cases where a button triggers a transition. In my scenario, I have a button that triggers a state change and I want the previous data to transition out befo ...

Removing cookies after sending a beacon during the window unload event in Chrome

Here's the situation: I need to make sure that when the browser is closed or the tab is closed, the following steps are taken: Send a reliable post request to my server every time. After sending the request, delete the cookies using my synchronous fu ...

Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" ...

The issue with CKEDITOR is that it fails to send data through ajax upon the initial submission

When using CKEDITOR, I am experiencing an issue where my forms do not send data to the server on the first submit. If I click the submit button once, empty fields are sent without any input from me. However, when I submit the form a second time, only then ...

What is the reason behind the success of chaining $q.when and $q.reject in Angular.js?

Why does this code not trigger the error callback when using $q in Angular.js: $q.when("test") .then($q.reject("error")) .then( function(v) { $scope.result = "Success: " + v; }, function(e) { $scope.result = "Failure: " ...

Combining the Powers of VueJs and Laravel

Currently, I am diving into Vuejs and building a feature that allows users to mark a message as their favorite. However, I've encountered the following error. Any guidance on how to resolve this would be highly appreciated. [Vue warn]: Failed to mo ...

Steps for resetting a div's display after adjusting the device size

I have a code that displays horizontally on desktop screens and vertically on phones. It includes an x button (closebtn) that is only displayed on phones to close the menu bar. How can I automatically display it again after resizing the page back to deskto ...

Tips for passing the name of a success function as a parameter in an AJAX request

My challenge is to create an AJAX call as a single function, where I pass the success function name as a parameter. Here's the function that I attempted: function MakeApiCall(dataText, apiName, functionName) { $.ajax({ url: apiUrl + apiName, ...

Using React to update state with a function that returns a value

I am facing an issue where the value returned by the function checkSuggestionList is not being passed to this.state.validSearchParentInput. It seems like the value is being set using setState before the function checkSuggestionList finishes executing. ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

Building a multilingual website using AngularJS UI-Router

I am currently working on developing a multilingual website using AngularJS. While providing translations in templates seems straightforward, I am facing challenges when it comes to implementing proper multilingual routes using UI-Router. Unfortunately, I ...

Trigger is not activated by dynamically created element

I am dealing with a block of code that is dynamic and looks like this. var li3 = document.createElement('li'); li3.classList.add("col-sm-3"); li3.classList.add("no_padding"); var inner = ""; inner = inner ...

Sending new props when navigating back using $navigateBack

I created an overview page where users can view their results. They have the option to edit a value by clicking on the edit button, which navigates them to another page for making changes. However, upon returning to the overview page after editing, I notic ...

Using Node.js, we can create a program that makes repetitive calls to the same API in a

My task involves making recursive API calls using request promise. After receiving the results from the API, I need to write them into an excel file. Below is a sample response from the API: { "totalRecords": 9524, "size": 20, "currentPage": 1, "totalPage ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

Replicating a tag and inputting the field content

Scenario: An issue arises with copying a label text and input field as one unit, instead of just the text. Solution Needed: Develop a method to copy both the text and the input field simultaneously by selecting the entire line. Challenge Encountered: Pre ...

Navigating through the fetch API request when using express js

I'm looking to use the fetch API to send requests and have those requests handled by Express JS. In my setup, I've put together server.js (Express JS), index.html (home page), and signin.html (sign-in page). index.html <!DOCTYPE html> < ...

increasing the efficiency of exporting large amounts of data in Laravel to prevent timeout errors

I need to create a monthly report based on a database containing thousands of records. Sometimes, users may request reports spanning multiple months. With the current record size, a month's worth of data can exceed 5000 entries. Currently, I am utili ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...