firebase - 为什么我的数据点没有放置在图表中的相应位置?
问题描述
我有一个 Nuxt 组件,它使用 加载图表chart.js
,填充来自 Firestore 数据库的数据。数据点在我的图表底部加载为一条平线。但是,悬停时数据具有不同的值范围。
如何让数据点呈现在正确的位置以生成实际图形?
loaded
在检索 Firestore 数据后,我尝试使用变量加载图表。我最终遇到了完全相同的问题。
在将数据推送到它之前,我尝试添加一些静态权重数组数据。这样做时,它准确地显示了这些点,但其余的平放在底部(悬停时仍显示有效的数据点值)。
<template>
<div id="container">
<canvas ref="chart"></canvas>
</div>
</template>
<script>
import { firebase, db } from '@/plugins/firebase'
import Chart from 'chart.js'
const color = ['#3AC', '#D91D63', '#5F6982', '#F4B651', '#3F4952']
export default {
data() {
return {
laoded: false,
weightData: [],
}
},
async mounted() {
// retrieve weight data from firebase
this.getWeightData()
const ctx = this.$refs.chart
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [{
data: this.weightData,
backgroundColor: color[0],
borderColor: color[0],
borderWidth: 1,
fill: false,
label: 'weight',
responsive: true
}]
},
options: {
legend: {
usePointStyle: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 10
}
}]
},
tooltips: {
callbacks: {
afterBody(tooltip, dataset) {
let data = 'goal: goal here'
return data
}
}
}
}
})
},
methods: {
getWeightData() {
firebase.auth().onAuthStateChanged(async user => {
if (user) {
const data = await db.collection('users').doc(user.uid).collection('weight').get()
.then(querySnapshot => {
if (!querySnapshot.empty) {
querySnapshot.forEach(doc => {
this.weightData.push(doc.data().weight)
})
}
})
}
})
this.loaded = true
}
}
}
</script>
weightData
我期望一个包含数组数据点的折线图。我得到的只是工具提示中具有不同值的平线。
此外,图表的范围是 0 到 1,即使weightData
值上升到 200。
解决方案
getWeightData()
异步填充weightData
,因此您必须在继续设置图表之前等待函数调用。
首先,将 1️⃣ 包裹起来getWeightData()
,Promise
这样您就可以返回获取的重量数据 2️⃣(而不是在 中设置this.weightData
)Promise
:
methods: {
getWeightData() {
return new Promise((resolve, reject) => { /* 1 */
firebase.auth().onAuthStateChanged(user => {
if (user) {
db.collection('users')
.doc(user.uid)
.collection('weight')
.get()
.then(querySnapshot => {
const weightData = []
if (!querySnapshot.empty) {
querySnapshot.forEach(doc => {
weightData.push(doc.data().weight)
})
}
resolve(weightData) /* 2 */
})
.catch(reject)
} else {
reject()
}
})
})
}
}
然后在 中mounted()
,存储3️⃣getWeightData()
中的等待结果:this.weightData
async mounted() {
this.weightData = await this.getWeightData() /* 3 */
/* now, setup chart with `this.weightData` */
}
推荐阅读
- ruby-on-rails - 如果未经授权,ActiveAdmin 设置自定义重定向路径
- java - Selenium InternetExplorerDriver 没有在窗口上获得焦点
- django - 如何使用 django rest 更改 oauth2 中令牌的 expiry_in 参数
- c++builder - 无法从“TFmxChildrenList”转换为“TRectangle *”
- java - 将字符串传递给另一个类中的 main 方法
- javascript - 猫头鹰滑块单击下一个前一个触发所有其他滑块滑动
- c# - float.NaN 的 DataAnnotations 属性
- jasper-reports - 如何通过将值传递为真或假来隐藏jasper报告中croostab中的特定行?
- google-visualization - 谷歌时间线 - 如何在当前日期中包含一条垂直线
- windows - 带有 ~ENABLE_LINE_INPUT 的控制台未通过 /r