FullStackOfPancakes
FullStackOfPancakes

Reputation: 1381

Loop through array in vue-chartjs

I'm working with Laravel 5.7 and have been using vue-chartjs.

Expected outcome:

I want to pass an array to Vue and loop through specific values to dynamically create a chart.

What I've been trying:

I have the following array:

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"
]

I'm passing the array to my Vue component using the :bind shorthand in my blade.

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

I was reading about using a sequential for loop, but whenever I try and add a for loop, I get an Uncaught Error: Module build failed: SyntaxError: Unexpected token (19:11) error.

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

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

  mounted() {
    console.log(this.chartData); // This works
    var length = this.chartData.length; // So does this
    
    this.renderChart({
      labels: ['Ratio Value'],

      // This produces the error listed above
      for ( var i = 0; i < length; i++ )
      {
        console.log(chartData[i]);
      }

      datasets: [
        // I want to dynamically produce the following
        {
          label: [chartData.order_date],
          data: chartData.ratio
        }
      ]
    })
  }
}
</script>

The array length is constant at 5, so I could just store their values in hidden inputs in my blade template and make use of document.querySelector, but this seems clunky and not the best route.

Any advice would be extremely appreciated!

Upvotes: 1

Views: 1260

Answers (1)

Camilo
Camilo

Reputation: 7184

Move your for() out of the renderChart() call:

import { Line } from 'vue-chartjs'

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

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

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

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

   this.renderChart({
      labels: labelsArray, // Reference our new labelsArray
      datasets: [
        {
          label: 'Ratio',
          data: ratioArray, // And our new ratioArray
        }
      ]
    })
  }
}

You can't call functions when initializing objects.

Upvotes: 2

Related Questions