【问题标题】:Charts.js: Moment is not defined (using chart.bundle.min.js)Charts.js:未定义时刻(使用 chart.bundle.min.js)
【发布时间】:2018-03-27 18:13:45
【问题描述】:

我已经成功创建了一个图表并使用charts.js 对其进行了配置,但现在我想让X 轴代表时间。当我尝试使用下面的代码执行此操作时,我收到以下控制台错误:Uncaught ReferenceError: moment is not defined。我使用的是chart.bundle.min.js,因为文档指定捆绑包中包含moment.js,因此我也不需要下载和链接moment.js。

这是代码,我是从一个回答有关时间轴的问题的堆栈成员那里得到的。 JavaScript:

function newDate(days) 
{
  return moment().add(days, 'd'); //THIS IS WHERE THE PROBLEM IS ACCORDING TO CONSOLE.
};

var config = 
{
  type: 'line',
  data: 
  {
    //Calling the function here, so also shows as error in console.
    labels: [newDate(-4), newDate(-3), newDate(2), newDate(3), newDate(4), newDate(5), newDate(6)], 
    datasets: 
    [{
      label: "My First dataset",
      data: [4, 3, 1, 4],
    }]
  },
  options: 
  {
    scales: 
    {
      xAxes: 
      [{
        type: 'time',
        unit: 'month',
      }],
    },
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

HTML:

<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <link rel="stylesheet" href="css/customFitStyling.css" type="text/css">
    <link rel="stylesheet" href="css/w3c_v4.css" type="text/css">
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="js/chart.bundle.min.js"></script>
  </head>
  <body>

    <canvas id="myChart"></canvas>
  </body>
</html>

【问题讨论】:

    标签: javascript chart.js momentjs chart.js2


    【解决方案1】:

    在我看来 Moment 出于某种原因在捆绑包中不可用我在 JSFiddle 中尝试过您的代码并且出现错误,但是在 Moment.js serpatley 中加载它工作得很好。

    也许使用 Chart.js 和 Moment.js 而不是捆绑包,如果您担心 http 请求,您总是可以自己压缩和捆绑它们?

    【讨论】:

    • 你是对的:包括 moment.js 单独工作。我应该在chart.js github上打开一个问题吗?
    • 这样做可能会有所帮助,1 你可能会发现你可以使用捆绑版本,但它可能在命名空间或类似名称后面,至少它可能会提醒他们它可能没有按预期工作。
    【解决方案2】:

    我查看了 charts.js 的文档:

    When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See Moment.js docs for details.

    所以,你应该像这样使用 Chart.js api:

    var chart = new Chart(ctx, { type: 'line', data: data, options: { scales: { xAxes: [{ type: 'time', time: { displayFormats: { quarter: 'MMM YYYY' } } }] } } })

    不是moment().add()

    【讨论】:

    • 感谢您的回答,我最初使用此方法构建了一个图表,但它没有按我想要的方式显示刻度或接受数据,即使有刻度和单位配置。
    猜你喜欢
    • 2017-11-20
    • 2016-01-05
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多