在vue-chartjs中循环遍历数组

问题描述 投票:1回答:1

我正在使用Laravel 5.7并且一直在使用vue-chartjs

预期结果:

我想将数组传递给Vue并循环遍历特定值以动态创建图表。

我一直在努力:

我有以下数组:

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

我正在使用刀片中的:bind shorthand将数组传递给我的Vue组件。

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

我正在阅读关于using a sequential for loop,但每当我尝试添加一个for循环时,我得到一个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 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>

数组长度恒定为5,所以我可以将它们的值存储在我的刀片模板中的隐藏输入中并使用document.querySelector,但这看起来很笨重而不是最好的路径。

任何建议将非常感谢!

javascript arrays laravel vue.js
1个回答
1
投票

将你的for()移出renderChart()电话:

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
        }
      ]
    })
  }
}

initializing objects时你不能调用函数。

© www.soinside.com 2019 - 2024. All rights reserved.