vue js挂载firebase异步调用不更新数据

时间:2018-05-28 15:08:13

标签: javascript firebase asynchronous vue.js

我知道问题是什么,但我无法在互联网上找到解决方案。所以我用firebase调用来自firebase的数据:

  

此$ store.dispatch(' getConsumptionFromFirebase&#39)。

但在我从firebase获取数据之前,我正在调用Doughnut.vue文件中的mounted()函数,因为当我转到其他组件并返回此处时,将呈现数据,因为它之前已加载。我该如何解决这个问题,我需要立即呈现数据。这是代码:

我的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>

1 个答案:

答案 0 :(得分:1)

我看到你通过调用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>