【问题标题】:VueJs/ChartJs - single file component computed property only renders when I click the component in Vue Dev ToolsVueJs/ChartJs - 单文件组件计算属性仅在我单击 Vue 开发工具中的组件时呈现
【发布时间】:2017-11-29 14:55:05
【问题描述】:

我有一个文件组件,它使用 Chart.Js 为一些硬编码数据呈现简单的可视化。我通过 index.html 的 head 部分中的 CDN 调用 Chart.Js 库。

我使用的是官方的 Webpack 模板。

由于某种原因,除非我单击 Vue Dev Tools 扩展中的组件,否则图表不会呈现。

我尝试将其从计算更改为创建/安装,但没有奏效。

这是我的代码。任何帮助使其正确渲染将不胜感激。

<template lang="html">
  <div>
    <div class="row">
      <div class="col-sm-12 col-md-4">
        <canvas id="carbChart"></canvas>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      calories: 3000,
      childSex: 'male',
      childAge: 'eighteen'
    }
  },
  computed: {
    nutrientCharts: function() {
      let calories = this.calories;

      let carbCtx = document.getElementById('carbChart').getContext('2d');

      let carbChart = new Chart(carbCtx, {
        type: 'doughnut',
        data: {
          labels: ['Low', 'Good', 'Too Much'],
          datasets: [{
            label: 'carbs',
            data: [calories * .45, calories * .65, calories * 1],
            backgroundColor: ['orange', 'blue', 'red']
          }]
        }
      });
    }
  }
}
</script>

【问题讨论】:

  • 计算属性是延迟加载的,因此在模板或 vue 实例代码的其他部分引用它们之前,它们不会被计算。您没有在任何地方引用 nutrientCharts,因此不会调用该方法。

标签: javascript webpack vue.js chart.js


【解决方案1】:

您已在 computed 属性中定义了该方法,但从未使用过它。

假设您只想让它运行,请在挂载时加载图表:

mounted() {
  this.nutrientCharts();
},
methods: {
  nutrientCharts: function () {
    // your code here
  }
}

【讨论】:

  • 很高兴听到它对您有所帮助 :)
猜你喜欢
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 2020-09-30
  • 2019-03-31
  • 2018-12-04
  • 1970-01-01
  • 2020-10-08
相关资源
最近更新 更多