Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project.

The goal:

I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values.

My approach so far:

Here's the array I'm working with:

0 => array:4 [▼
  "order_date" => "2019-04-01"
  "days_remaining" => 29
  "cash_remaining" => 26714.63
  "ratio" => "1.11"
]
1 => array:4 [▼
  "order_date" => "2019-04-02"
  "days_remaining" => 28
  "cash_remaining" => 26184.61
  "ratio" => "1.41"
]

To pass this array to my Vue component, I am using the :bind shorthand in my blade template.

:chart-data="{{ json_encode($array) }}"

I came across suggestions about using a sequential for loop, but attempting to implement a for loop led to an error message:

Uncaught Error: Module build failed: SyntaxError: Unexpected token (19:11)
.

<script>
import { Line } from 'vue-chartjs' 

export default {
  extends: Line,
  props: ['chartData'],

  mounted() {
    console.log(this.chartData); // This functioned as expected
    var length = this.chartData.length; // Similarly successful
    
    this.renderChart({
      labels: ['Ratio Value'],

      // The for loop attempt resulted in the above error
      for ( var i = 0; i < length; i++ )
      {
        console.log(chartData[i]);
      }

      datasets: [
        // My intention is to dynamically create the following
        {
          label: [chartData.order_date],
          data: chartData.ratio
        }
      ]
    })
  }
}
</script>

The array size remains constant at 5, which could allow me to store their values in hidden inputs within my blade template and leverage document.querySelector. However, this method feels cumbersome and suboptimal.

I would greatly appreciate any guidance or suggestions!

Answer №1

It is important to remember to move your for() loop outside of the renderChart() function:

import { Line } from 'vue-chartjs'

export default {
  extends: Line,
  props: ['chartData'],

  mounted() {
    var length = this.chartData.length;
    var array = this.chartData;

    // Initialize new arrays to store the data
    var ratioArray = [];
    var labelsArray = [];

    for (var i = 0; i < length; i++) {
      // Add data to the new arrays
      labelsArray.push(array[i] ? array[i].order_date : '');
      ratioArray.push(array[i] ? array[i].mbr : '');
    }

   this.renderChart({
      labels: labelsArray, // Use the updated labelsArray
      datasets: [
        {
          label: 'Ratio',
          data: ratioArray, // Update with the new ratioArray
        }
      ]
    })
  }
}

Remember that you cannot call functions when initializing objects.

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

The program is designed to only allow up to two images to be wrapped

I'm struggling with a short jQuery program that I need help with. The problem is, I can't seem to get it to wrap more than two images in the same row. My goal is to create a website that side-scrolls, and I thought this approach would be the simp ...

Using references to pass variables in TypeScript [Angular 8]

I have several variables within the html of this component that are assigned their values by the typescript file. The declaration in the html is as follows: <h1>{{myproperty1}}<\h1> <h1>{{myproperty2}}<\h1> <h1>{{myp ...

Vue.js does not support sorting columns

In this specific codepen example, I have created a Vue table that allows for sorting by clicking on the column name. Although I can successfully retrieve the column name in the function and log it to the console, the columns are not sorting as expected. Wh ...

Top method for creating integration tests in React using Redux and Enzyme

Currently, I am working on setting up integration tests within my application. There are a few API calls that occur both when the component mounts and upon a button click. The response from these API calls is stored in the app's store, which then upd ...

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

What is the significance of having nodejs installed in order to run typescript?

What is the reason behind needing Node.js installed before installing TypeScript if we transpile typescript into JavaScript using tsc and run our code in the browser, not locally? ...

Utilize JSON data loading instead of directly embedding it onto the page for improved website

I've integrated Mention.js into my website, allowing a dropdown list of usernames to appear when "@" is typed in a designated textarea. <textarea id="full"></textarea> While it's functioning well, the examples provided only show how ...

The click event fails to provide $event upon being clicked

Within my HTML structure in an angular 7 application, I have the following setup: My goal is to trigger the GetContent() function when any text inside the div is clicked. Strangely, when clicking on the actual text, $event captures "Liquidity" correctly. ...

Tips for displaying data using AJAX in Vuejs 2

When attempting to set data in a Vue instance, I encounter difficulties. For example, when assigning values to the data property via AJAX, I am able to render the exam object. However, I face an error when trying to access an inner array with exam.question ...

What is the way to modify the contents of a div using ajax?

I have blade files in both list and image formats. There are two span buttons here, and I would like to display a list in different formats when each button is clicked. How should I go about writing the code for this? <span id="penpal-image-view" ...

Leveraging functions with Ng-Repeat

I am currently dealing with two different arrays of objects. The first array contains a list of permissions groups, while the second array consists of user groups. My main goal is to compare the Group Owner (which is represented by ID 70) with the list of ...

Using the Vue v-text directive to combine text from different variables

I have been attempting to merge two string values into a element, but haven't had any luck so far. The following code works fine:</p> <pre><code><v-toolbar-title class="hidden-sm-and-down font-weight-light" v ...

Tips for implementing an if else statement in ReactJS while utilizing the useEffect hook

Below is the code snippet for returning a Plotly graph. I would like to display a message or alternative layout when there is no data available for the graph, such as showing "No data available". How can I achieve this? import React, { useEffect } from ...

One project contains a pair of React instances

I am currently working on a React Web App and recently encountered an issue with an 'invalid hook call' error. Upon further investigation, I discovered that there are duplicate copies of the React library in my project, including within the CSS f ...

Display serial numbers in a dynamic manner within a Vue component

I am currently working on a project that involves a quiz-style interview with different sets of questions tailored to three types of users. Each user can have multiple roles, so if they select more than one role, they should see questions from all selected ...

Execute the dynamic key API function

Below is the data object: registration: { step1: { project: '', }, step2: { adres: '', facade: '', floor: '', }, }, An attempt is being ...

The icon in Material UI button is missing from the display

The button is functional, but the icon inside it isn't displaying correctly: Here is the code for the button: <Button color="secondary" aria-label="add an alarm"> <AlarmIcon></AlarmIcon> </Button> <But ...

The React Vite application encountered an issue: There is no loader configured for ".html" files at ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html

**Encountered errors in a React Vite web app** ** ✘ [ERROR] No loader is configured for ".html" files: ../server/node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html ../server/node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js:86 ...

What is the best way to retrieve a file using XMLHTTPRequest and Ajax?

I am currently using window.location.href to download a file, but this method requires a second call to my servlet which takes about 1 minute to generate the file. How can I download the file using XMLHTTPRequest instead? The solution should only work wi ...

Vue component prop values are not properly recognized by Typescript

Below is a Vue component I have created for a generic sidebar that can be used multiple times with different data: <template> <div> <h5>{{ title }}</h5> <div v-for="prop of data" :key="prop.id"> ...