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

Implementing Pagination in Vuetify: A Step-by-Step Guide

I am looking to implement pagination using the Vuetify framework in my VueJS project. The Vuetify Pagination component: <v-pagination v-model="pagination.page" :length="pagination.total / 5" :total-visible="pagination.visible" ...

Tips for fixing a type error in javascript/cypress

While learning cypress and javascript, I encountered this type error: TypeError: _testElements.default.selectionRow is not a function I have thoroughly reviewed the documentation for cypress but cannot seem to find any errors in my code. I'm hoping ...

Convert SQL query results into an array

I'm facing an issue with a SQL query select array(select distinct request_at from trip) as datas; with q as (select sum(case when request_at = datas[1] then 1 else 0 end) as total from trip) select * from q I'm attempting to create a large datas ...

Having trouble with a one-dimensional array of multiples of 5 in my coding practice. It's a new concept for me and I'm

Here is the task at hand: Create a program that will assign and store the first 20 multiples of 5 in an array called Data. No other array can be used in this program. The program should output the elements of the array as follows: a) Write only the com ...

issues with the redirection functionality in the Play framework

I am currently working on an application that extracts data from Twitter profiles. I want to give the user the ability to select which parts of their profile should be used (for example, excluding tweets). To accomplish this, I plan to incorporate checkb ...

Mastering Protractor: Opening multiple sites and sending keys

My current task involves creating a script with a list of websites and corresponding amounts in a JSON format: { "URL": [{ "https://testing.com/en/p/-12332423/": "999" }, { "https://testing.com/en/p/-123456/": "123" ...

The issue I'm facing with Angular 8 is that while the this.router.navigate() method successfully changes the URL

As someone who is relatively new to Angular, I am currently in the process of setting up the front end of a project using Angular 8. The ultimate goal is to utilize REST API's to display data. At this point, I have developed 2 custom components. Logi ...

An issue has been encountered in NodeJS with a route that begins with a percent sign causing an error

I have a NodeJS server set up with the following backend configuration: app.use(express.static(__dirname)) app.get('/', function(req, res){ res.send('main page here') }); app.get('/*', function(req, res){ res.send(&apos ...

Tips on invoking a mixin within a Jade template showcased in a Node/Express endpoint

I'm currently developing a component that I plan to use multiple times on a website through a Jade template. This is how my route is set up: router.get('/', function(req, res, next) { res.render('indicators',{category:"", num ...

Utilizing the outcome of an AJAX call in JavaScript

I am facing an issue with a query that is returning 2 rows. Below is my PHP code snippet: $arr = array(); $stmt = $dbh_conn->prepare("SELECT id,name FROM mytable WHERE id <= 2"); $stmt->execute(); $result = $stmt->fetchAll(); /*Array ( ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

Tips for ensuring the directive stays current with changes to the parent scope variable

Example: <div ng-show="{{ display }}"> ... </div> angular.module('mymodule').directive('mydirective', [ function () { return { scope: { display: '=' }, ... }; ...

Preventing the page from scrolling to the top while utilizing an Angular-bootstrap modal and a window position:fixed workaround on an iPad

It's common knowledge that there is a bug in bootstrap modals on certain devices, causing the page behind the modal to scroll instead of the modal itself (http://getbootstrap.com/getting-started/#support-fixed-position-keyboards) An easy fix for this ...

Performing a fetch() POST request in Express.js results in an empty body object being generated

Purpose: Implement a function in fetch() to send specified string data from the HTML document, for example "MY DATA" Here is the code snippet: HTML Code: <!DOCTYPE html> <html> <body> <script type="text/javascript"> function ...

Encountering a problem while trying to execute npm run serve on a newly created Vue-CLI project

Struggling to execute npm run serve on a fresh vue Project made with the Vue CLI. I initiated the project using vue create app, navigated to the project directory cd app, and ran npm run serve, a routine I have followed in previous projects. However, start ...

Executing a function when a specific element is triggered within an ng-repeat in AngularJS

Hey there, I've been grappling with changing the limitTo filter on a specific list, but I'm encountering an issue: whenever I trigger the filter change, it applies to all ng-repeated categories. The function within my main controller is as foll ...

Django views functions do not receive any data during execution

Things are running smoothly, but it appears that the post function in views.py is not receiving any data. Also, how can I create a submit button using pure JavaScript without reloading the page? views.py: from django.shortcuts import render from rest_frame ...

Launching an online platform with Express and Ember frameworks

I am embarking on a project to create a straightforward CMS using Node.js (with Express) and Ember.js. While I have experience with Angular, I am new to Ember.js. I've noticed that Ember.js operates similarly to Angular in terms of its CLI reliance, a ...

Is there a way to retrieve the JSON url from the input box

My goal is to retrieve a JSON file from a URL entered in a text box. I have identified the text box as txtr and used jQuery to get the value like this: var txtbval = $("#txtr").val();. I then included this value in the JSON parsing script as follows: url: ...

What is the best way to send variables from one page to another using jQuery or Javascript?

Is there a way to use POST with jQuery/Javascript to send data to another page and then redirect to that page? Instead of using GET... Using Javascript window.location = 'receivepage.php?variable='+testVariable; Once it's received by PHP ...