【问题标题】:Vuejs data not showing properly on mountedVuejs 数据在挂载时未正确显示
【发布时间】:2018-06-22 09:08:30
【问题描述】:

我是 Vuejs 的新手。我用 Vue、Firebase 开始了一个项目,并在其中使用了 Chart Js。这是问题的详细信息。

如果我在 data() 中给出 sales_today 的任何值,它会正确显示在我使用 this.sales_today 的安装位置上也可以完美地在模板 {{sales_today}} 中。

但在 Created 中,我正在尝试通过 firebase 查询的输出来更改此值。sales_today 值。然后输出完美地显示在模板 {{sales_today}} 中,但在此处安装的内容中不起作用

 **data: [this.sales_today,30,60,10]**      

模板

<template>
   {{sales_today}}
</template>

数据

data(){
  return{
        sales_today:''            
    }
},

已安装

mounted() {
    data: {
         datasets: [{                     
               data: [this.sales_today,30,60,10],                        
         }]
    }    
}

已创建

created(){
     let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
       .get()
       .then(snapshot => {
        var total = 0;
        snapshot.forEach(doc => {
           total += Number(doc.data().price)
        })
        this.sales_today = total
     })
}

这是完整的代码 https://github.com/Shakilzaman87/pukucrm/blob/master/src/components/dashboard/Dashboard.vue

【问题讨论】:

  • 自从创建后你发出了一个异步请求,响应来得太晚了,所以 this.sales_today onmounted 具有旧值
  • 你能告诉我如何解决这个问题吗?
  • 最简单和最快的方法是将代码从 created on Mounted 和设置 this.sales_today = total 之后,将之前的代码放在 mount 上,这样你就可以初始化图表收到回复后
  • 我不明白你的mounted 方法,为什么你的data 会这样?
  • 更好更正确的方法是使用 async 和 await ,我认为您可以使用 firebase 来做到这一点,并且基本上 created 将在收到响应后移动,因此您将拥有 this.sales_today onmount

标签: firebase vue.js chart.js


【解决方案1】:

这应该在mounted() 上。我没有cmets上的编辑器,我会在这里回答。

let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
   .get()
   .then(snapshot => {
    var total = 0;
    snapshot.forEach(doc => {
       total += Number(doc.data().price)
    })
    this.sales_today = total;

        var chart = this.$refs.chart;
        var ctx = chart.getContext("2d");
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels:this.labels,
                datasets: [{
                    label: 'Sales of June',
                    data: [this.sales_today,30,60,10],
                    backgroundColor: [
                        '#ffffff'
                    ],
                    borderColor: [
                        '#1976d2'
                    ],
                    borderWidth: 3
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            },
        });


 })

附:检查控制台是否有错误

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 2019-08-09
    • 2012-06-26
    • 1970-01-01
    • 2017-03-28
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多