我正在尝试绘制我的数据库中的一些数据。我正在关注结构的this jsfiddle。然而,即使我设法从我的API正确获取数据,图表也显示但没有绘制数据。
我的app.js看起来像这样:
// Load Sessions
var sessions = new Vue({
el: '#sessions',
delimiters: ["v{","}"],
data: { date:'', sessions:'', json:'', timestamp:''},
methods: {
loadSessions: function(){
var vm = this
axios.get('/api/v1/metrics/')
.then(function(response) {
vm.json = response.data
Highcharts.chart('container', {
chart: {
zoomType: 'x'
},
title: {
text: 'Session Over Time'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Sessions'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'Sessions',
data: vm.json
}]
});
})
}
}
})
vm.json
文件如下所示:
[ { "date": "2017-01-02", "timestamp": 1483401600, "sessions": 1100 }, { "date": "2017-01-03", "timestamp": 1483488000, "sessions": 1159 }, { "date": "2017-01-04", "timestamp": 1483574400, "sessions": 1084 }]
我在html中加载了一个简单的vue:
<div id='sessions'>
<a class="button is-primary" @click='loadSessions'>Load Sessions</a>
<!-- Just to test that data is loaded correctly from API -->
<ul style="margin-left: 20px;">
<li v-for="item in json">
<b>Date: </b> v{item.date} <br />
<b>Sessions:</b> v{item.sessions} <br />
<b>Timestamp:</b> v{item.timestamp}
</li>
</ul>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</div>
现在我认为我的问题在于格式化json,不是吗? jsfiddle示例中的on看起来有点不同。如何才能显示我的数据?
答案 0 :(得分:1)
您可以将数据转换为示例中显示的格式。
series: [{
type: 'area',
name: 'Sessions',
data: vm.json.map(d => [new Date(d.date).getTime(), d.sessions])
}]
我将您的date
属性转换为Javascript Date对象以使用getTime
,因为您的timestamp
属性(不管它来自何处)都不是正确的Javascript时间戳。