【问题标题】:How to dynamically add points to a bar/pie chart in a Vue context?如何在 Vue 上下文中向条形图/饼图动态添加点?
【发布时间】:2018-03-30 08:39:27
【问题描述】:

我想引导一个 Highcharts 条形图,然后在其中添加一些点(在 Vue 容器中)。文档中提到了 addPoint()setData()update() 作为实现这一目标的手段,但我尝试的所有咒语都没有奏效。

用于更新后饼图的demo 使setData() 的使用变得简单:

var chart = Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },

  series: [{
    data: []
  }]
});


// the button action
$('#button').click(function() {
  chart.series[0].setData([129.2, 144.0, 176.0]);
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div>
<button id="button" class="autocompare">Set new data</button>

我试图在 Vue 上下文中复制它,但图表从未更新

var chart = Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },

  series: [{
    data: []
  }]
});


new Vue({
  el: "#app",
  data: {},
  mounted() {
    chart.series[0].setData([129.2, 144.0, 176.0]);
    chart.redraw()
  }
})
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  <div id="container" style="height: 400px"></div>
</div>

【问题讨论】:

    标签: javascript highcharts vue.js


    【解决方案1】:

    看来调用Highlights.chart 会立即查询DOM,所以在调用Vue 的mounted 回调之前这样做会失败,因为该元素还不存在。那,或者它被 Vue 的渲染覆盖。相反,您需要在 Vue 挂载之后调用该函数。

    作为奖励,这里有一个小演示(我玩得很开心),它展示了该库如何与 Vue 一起使用。它使用watcher 在相应属性更改时重绘图表。

    function createChart() {
      return Highcharts.chart('container', {
        chart: {
          type: 'pie'
        },
        series: [{
          data: []
        }]
      })
    }
    
    
    new Vue({
      el: "#app",
      data: {
        chartData: []
      },
      mounted() {
        this.chart = createChart()
        this.setData([100, 100, 100])
      },
      methods: {
        setData(data){
          this.chartData = data
        }
      },
      watch: {
        chartData(data) {
          this.chart.series[0].setData(data)
          this.chart.redraw()
        }
      }
    })
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    <div id="app">
      <button @click="setData([129.2, 144.0, 176.0])">Show First Dataset</button>
      <button @click="setData([180, 100.0, 20.0])">Show Second Dataset</button>
      <div id="container" style="height: 400px"></div>
    </div>

    【讨论】:

      【解决方案2】:

      您可以使用 highcharts-vue,它是 highcharts 库的一个包装器。 以下是依赖项:“highcharts”:“6.1.0”, “highcharts-vue”:“1.0.4”, “vue”:“^2.5.2” 演示 - https://codesandbox.io/s/highcharts-vue-demo-forked-ewn4n

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多