html 如何在Vue.js库中使用Google Charts?

3pmvbmvn  于 7个月前  发布在  Vue.js
关注(0)|答案(3)|浏览(83)

我试图使用Vue.js库用Google Charts制作一个图表,但我不知道如何添加到div。
在这里我尝试做的,这是如何添加一个图表与香草JavaScript(Here the code example of the documentation),我试图适应vue,但没有发生:

google.charts.load('current', {'packages': ['corechart']});

Vue.component('line-char', {
    data: function(){
        // Create the data table.
        var data = google.visualization.arrayToDataTable([
            ['Tiempo', 'Temperatura'],
            [1,  1000],
            [2,  1170],
            [3,  660],
            [4,  1030]
        ]);

        // Set chart options
        var options = {
            'title': 'Data Line',
            'width': '100%',
            'height': 250,
            legend: { position: 'bottom' }
        };

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    },
    template: '<div v-model="chart_div"></div>'
});

字符串
html:

<div id="component">
    <line-chart></line-chart>
</div>

z9ju0rcb

z9ju0rcb1#

你需要做的是为你的<div>使用一个ref,然后注册一个回调函数来在你的组件的mounted钩子中绘制图表。

// Load library
google.charts.load('current', {'packages':['corechart']})

const lineChartOptions = {
  title: 'Data Line',
  width: '100%',
  height: 250,
  legend: { position: 'bottom' }
}

Vue.component('LineChart', {
  template: `<div ref="chart"></div>`, // 👈 set ref here
  data: () => ({
    headings: ['Tiempo', 'Temperatura'],
    chartData: [
      [1,  1000],
      [2,  1170],
      [3,  660],
      [4,  1030]
    ]
  }),
  methods: {
    drawChart () {
      const dataTable = google.visualization.arrayToDataTable([
        this.headings,
        ...this.chartData
      ], false) // 👈 don't forget "false" here to indicate the first row as labels

      const chart = new google.visualization.LineChart(this.$refs.chart) // 👈 use ref here
      chart.draw(dataTable, lineChartOptions)
    }
  }
  mounted () {
    // set the library loaded callback here
    google.charts.setOnLoadCallback(() => this.drawChart())    
  }
})

字符串
正如Matt所提到的,如果您的组件的模板对于单个<div>来说确实是空的保存,则可以使用$el属性来挂载图表,而不必担心引用

Vue.component('LineChart', {
  template: `<div></div>`,
  // ...
  methods: {
    drawChart () {
      // ...
      const chart = new google.visualization.LineChart(this.$el)
      chart.draw(this.dataTable, options)
    }
  }
})

9nvpjoqh

9nvpjoqh2#

根据更新,此解决方案不再可取

更简单的用法是使用vue-google-charts插件
示例代码:

<GChart
    type="ColumnChart"
    :data="chartData"
    :options="chartOptions"
  />

个字符

slsn1g29

slsn1g293#

innerHTML将允许您自定义工具提示,使其具有响应性,只需确保DOM是唯一的,内容被正确销毁以呈现在正确的组件上

相关问题