What is the best way to load varying datasets into a chart without relying on the observer "trickery" with vuecharts.js?

I am currently utilizing charts.js for Vue and facing an issue with pushing a variable number of datasets (including background color, data, and label) to a chart. I expect the data object to be logged as shown in this link, but unfortunately, the datasets include an extra observer object causing the charts not to render. Take a look at my code snippet:


let dynamicDataCollection = [];
        for (i =0; i < allDeptNames.length; i++) {
            let datasets = [
                {
                    label: allDeptNames[i],
                    backgroundColor: barColours[i],
                    data: [spaceIterationIns[i].length] 
                }
            ]
            dynamicDataCollection.push(datasets);
        }
        that.datacollection2 = {
            labels: ['Weekly'],                
            datasets: [                              
            ]
        }
        that.datacollection2.datasets = dynamicDataCollection;
        console.log(that.datacollection2);

This is how my data object looks like:

data () {
    return {
        windowWidth: 0,
        windowHeight: 0,
        datacollection2: null,
        chartData: { 

        }, chartOptions: {

        }         
    }
},

Here's a glimpse of my template setup:

<charts  v-if="last7DaysSelected" ref="visits_per_dept_bar"
             :css-classes="'visitsChart_bar'" 
             :chart-id="'visits_per_dept_bar'" 
             :height="150" 
             :options="chartOptions"
             :chart-data="datacollection2" 
></charts>

In addition, here is my chart.js file:


import {Line, mixins } from 'vue-chartjs'
Chart.defaults.global
let chartOptions = Chart.defaults.global;
chartOptions.defaultFontFamily= "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Helvetica Neue', sans-serif"

const { reactiveProp } = mixins
export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],

  mounted () {
    let that = this;

    that.chartOptions = { 
      scales: {
        yAxes: [{
            ticks: {
                suggestedMin: 0,      
            },       
        }],
        xAxes: [{
            ticks: {
                suggestedMin: 0,    
            },
        }],
    },
    legend: {
        labels: {
            fontColor: 'rgb(168, 119, 181)',
        }
    }
  },
    this.renderChart(this.chartData, that.chartOptions)
  }
}

Furthermore, this is what my current output objects show: https://i.sstatic.net/c7eZm.jpg

For an expanded view, check out: https://i.sstatic.net/7vJpj.jpg

It seems like Vue is attempting to work its reactivity magic, but it's causing issues by including the {_ ob _} object. Is there a way to render the chart with a variable number of datasets without encountering this problem? I've tried preventing the observer object, but it seems necessary due to vue.charts.js requiring reactivity. Any suggestions on how to possibly handle the for loop differently within the datacollection2 object rather than just pushing dataset objects to it?

Answer №1

It is advised to use options instead:

name: 'myComponent',
data: () {
  return {
    some: 'properties'
  }
},
nonReactiveData: {
  whatever: 'you prefer'
}

This method essentially sets up your component with an option called nonReactiveData. This can then be utilized in your HTML like this:

<some-component :data="$options.nonReactiveData">

If you require it in your script, you can do so like this:

methods: {
  someMethod() {
    console.log(this.$options.nonReactiveData)
  }
}

I hope this explanation proves helpful :)

Answer №2

Resolved the issue by combining the contents of the dynamicDataCollection Object:

     that.dynamicDataCollection = [];
        for (i =0; i < allDeptNames.length; i++) {
            let datasets = [
                {
                label: allDeptNames[i],
                backgroundColor: barColours[i],
                data: [spaceIterationIns[i].length] 
                }
            ]
            that.dynamicDataCollection.push(datasets);
        }
// this section
        let dynamicFlat = [].concat.apply([], that.dynamicDataCollection)  
        that.datacollection2 = {
            labels: ['Weekly'],                
            datasets: [                           
            ]
        }
// then here
        that.datacollection2.datasets = dynamicFlat;

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

Namespace remains ambiguous following compilation

I'm currently developing a game engine in TypeScript, but I encountered an issue when compiling it to JavaScript. Surprisingly, the compilation process itself did not throw any errors. The problem arises in my main entry file (main.ts) with these ini ...

Instructions on how to successfully send an AJAX request without having to open the webpage while utilizing Google App Engine

When sending AJAX requests without having to open a webpage on Google App Engine, you can utilize JavaScript libraries like jQuery $.ajax or $.post. However, if you want to send an AJAX request and receive the return value without opening a webpage, espec ...

Assess JavaScript for Fetch API implementation

Currently, I am utilizing node.js on Windows with the express module to create an HTML page where I need to retrieve data from a server-side function called getfiledata() (I want to keep my Javascript and text file private). I have attempted to use fetch( ...

Utilize the NPM Python Shell Callback Feature within Electron

I have a Python script that reads RFID tags when executed in the Python shell. Everything works fine with the script, but I'm facing an issue where I want to display "testing" using console.log() after the script is executed (when the tag is placed ov ...

Explore the intricacies of complex hierarchies

<table id="financial101_tab1" class="dxrpControl_Moderno dxrpWithoutHeader_Moderno"> <tbody> <tr> <td id="financial101_tab1_RPC" class="dxrp dxrpcontent"> <input id="BlockControlfinancial101_tab1ATI" type= ...

Load the file once the previous load has finished

I have a scenario where I need to load a file into an id, and once that is done, I want to load another file into an id within the first load. Does that sound a bit complicated? To better illustrate, let's look at the code snippet below: function i ...

Organize the menu in Angular by sorting it alphabetically

I am currently exploring a way to organize the buttons inside the menu in alphabetical order using a function in the TypeScript file. Please see the code snippet below, which utilizes Angular Material. <mat-menu #menu3="matMenu" [overlapTrig ...

What is the process for aligning rows with the selected option from the drop-down menu

Alright, so here's the scenario: I have created a table along with two drop-down filters. The first filter is for selecting the Year, and it offers options like "All", "2023", "2022", and "2021". When I pick a specific year, let's say "2022", onl ...

Stopping a function when another function is invoked in JavaScript

I've been immersing myself in the search for a way to halt one function if another is called or triggered in JavaScript. Initially, I believed it to be unattainable, but I'm open to having my perspective changed. My current focus lies within a t ...

Simplified method for utilizing plugins with the composition api in vue 3

When incorporating vuex or vue-router as plugins in Vue and utilizing the options API, access to these plugins can be achieved using the this keyword. main.js import { createApp } from 'vue'; import i18n from '@/i18n'; import router fr ...

Adjust the color of the upcoming line I am sketching without ending the path

I am working on a paint program and encountered an issue. My goal is to create buttons of various colors that can change the color of the next stroke drawn by the user. While searching for a solution, I came across a similar question (HTML5 Canvas change ...

Adjust your path by 45 degrees

I'm facing a challenge in getting all three of my images to fly off the screen in different 45-degree directions. Currently, they are all flying off the screen to the left, but I would prefer them to go in 45-degree angles. I've shared the CSS, H ...

Encountering a problem with AngularJS

My AngularJS test is running fine, but I keep getting this error in the console!! Error: [filter:notarray] Expected array but received: {"data":[{"brand":"Samsung A7 Prime","color":"Gold","price":24500,"img":"img/Chrysanthemum.jpg"},{"brand":"iPhone 6 P ...

Display various v-dialog boxes with distinct contents in a vue.js environment

Hello there! I am currently working on customizing a Vue.js template and I have encountered an issue with displaying dynamic v-dialogs using a looping statement. Currently, the dialog shows all at once instead of individually. Here is the structure of my ...

Concealing Panels within EasyUi Tab Navigation

There is an easyui Tab that consists of 4 tabs. After receiving a response from the server, it may be necessary to hide or show some of the tabs. I attempted to remove the tabs initially and add them back later. However, the issue arises when the tabs are ...

Altering information with the use of history.pushState throughout time

I've created a template that I want to load using the jQuery .load() function. However, during testing, I discovered that it's not loading at all. Here is the code I'm trying to use for loading: function open() { history.p ...

Using JQuery for manipulating server controls

I've been working on a jQuery function that interacts with HTML controls $(document).ready(function(){ $('#mydropdown').change(function(){ $selected_value=$('#mydropdown option:selected').text(); $( ...

``The vuejs component encountered an error when trying to dispatch an action with an unknown action type in vu

I've successfully implemented laravel, vue, and vuex in a different project with similar code, and it's been running smoothly. Now, I'm trying to adapt that code as a boilerplate for this project, but I'm encountering the following erro ...

Encrypting data using NodeJS Crypto and decrypting it in front-end JavaScript

I'm currently on the hunt for a way to perform AES256 CBC decryption on the client side. When working with nodeJS, I typically utilize this function for encryption: exports.encrypt = function(txt, cryptkey){ var cipher = crypto.createCipher(' ...

My AJAX requests do not include any custom headers being sent

I'm facing an issue with making an AJAX request from my client to my NodeJS/ExpressJS backend. After firing the request, my backend successfully receives it but fails to recognize the custom headers provided. For example: $.ajax({ type: " ...