javascript - 如何在 Vue.js 库中使用 Google Charts?
问题描述
我正在尝试使用 Vue.js 库使用 Google Charts 制作图表,但我不知道如何添加到 div。
这是我试图做的,这是如何使用香草javascript添加图表(这里是文档的代码示例),我试图适应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>
解决方案
你想要做的是使用ref
你的<div>
,然后注册一个回调来在你的组件的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
属性来挂载图表而无需打扰 refs
Vue.component('LineChart', {
template: `<div></div>`,
// ...
methods: {
drawChart () {
// ...
const chart = new google.visualization.LineChart(this.$el)
chart.draw(this.dataTable, options)
}
}
})
推荐阅读
- python - NumPy 中的索引:访问每组其他值
- mysql - 仅为用户或数据库禁用 ONLY_FULL_GROUP_BY MySQL 模式
- java - 选择所有在休眠状态下不起作用的查询
- azure - 在 azurerm_automation_account 中寻找可选 sku 变量的 terraform 模块参考
- python - 如何在python3中获取protobuf的RepeatedCompositeContainer或RepeatedScalarContainer包含的类型?
- php - 使用 preg_match 您可以剪切不同句子的特定部分
- python - 在 Django 中过滤查询集的子集
- azure - 如何在 Azure 中的数据盘上配置文件系统?
- apache-kafka - 确保已使用 REST 代理从 Kafka 主题读取所有消息
- javascript - javascript 异步/等待和承诺