我正在使用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
,但这似乎很笨拙,不是最好的选择路线。
任何建议将不胜感激!
答案 0 :(得分: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时不能调用函数。