javascript - vue js挂载firebase异步调用不更新数据
问题描述
我知道问题是什么,但我无法在互联网上找到我的案例的解决方案。所以我用这条线从firebase调用数据:
this.$store.dispatch('getConsumptionFromFirebase')
但是我在 Doughnut.vue 文件上的 mount() 函数在我从 firebase 获取数据之前被调用,因为当我转到其他组件并返回这里时,数据将被渲染,因为它之前已加载。我该如何解决这个问题,我需要立即呈现数据。这是代码:
我的 mainComponent.vue 文件:
<Doughnut class="chartSize" :labels="labelsDoughnut" :data="dataDoughnut" :colors="backgroundColorDoughnut"></Doughnut>
<script>
import { mapGetters } from 'vuex'
import Doughnut from '@/components/Graphs/Doughnuts'
export default {
components: {
Doughnut
},
data () {
return {
labelsDoughnut: [ 'Air Conditioning & Heating', 'Cleaning Appliances' ],
backgroundColorDoughnut: [ '#41B883', '#E46651' ]
}
},
computed: {
...mapGetters({
airConditioningHeatingMonthlyConsumption: 'airConditioningHeatingMonthlyConsumption',
cleaningAppliancesMonthlyConsumption: 'cleaningAppliancesMonthlyConsumption'
}),
dataDoughnut: function () {
return [ this.airConditioningHeatingMonthlyConsumption, this.cleaningAppliancesMonthlyConsumption ]
}
},
created () {
this.$store.dispatch('getConsumptionFromFirebase')
}
}
</script>
我的 Doughnut.vue 文件:
<script>
import { Doughnut } from 'vue-chartjs'
export default {
props: ['labels', 'data', 'colors'],
extends: Doughnut,
data () {
return {
chartOptions: {
legend: {
position: 'top'
}
},
dataCollection: {
labels: this.labels,
datasets: [ { data: this.data, backgroundColor: this.colors } ]
}
}
},
mounted () {
this.renderChart(this.dataCollection, this.chartOptions)
}
}
</script>
解决方案
我看到您通过调用手动渲染组件this.renderChart(this.dataCollection, this.chartOptions)
因此,使用计算而不是数据可能是一个好主意,并注意:
<script>
import { Doughnut } from 'vue-chartjs'
export default {
props: ['labels', 'data', 'colors'],
extends: Doughnut,
computed: {
chartOptions () {
return {
legend: {
position: 'top'
}
}
},
dataCollection () {
return {
labels: this.labels,
datasets: [ { data: this.data, backgroundColor: this.colors } ]
}
}
},
mounted () {
this.renderChart(this.dataCollection, this.chartOptions)
},
watch: {
chartOptions: function () {
this.renderChart(this.dataCollection, this.chartOptions)
},
dataCollection: function () {
this.renderChart(this.dataCollection, this.chartOptions)
}
}
}
</script>
推荐阅读
- automated-tests - 如何在没有 .vwf/.bdf 文件的情况下“自动”测试我的实体
- haskell - 更改变量类型以匹配预期类型
- terraform - terraform route53 解析器设置
- node.js - 使用 VS Code 调试时如何解决“ReferenceError: Office is not defined”?
- mongodb - 如何在 MongoDB 中针对其他集合数据进行排序
- google-signin - 无法解析方法“setAllowNewEmailAccounts(boolean)”
- c# - 在运行时访问 DisplayClass 对象的属性
- c++ - boost ptree read_ini 使独立应用程序崩溃
- dialogflow-es - 从 zip 导入后,无法将 Dialogflow 与 Google Assistant 集成
- python - 如果数据中存在与某些条件匹配的另一行,则从 pandas DataFrame 中查找行