Vue项目中使用HighChart
记:初次在Vue项目中使用 HighChart 的时候要走的坑
感谢这位哥们的思路 传送门
Vue-cli项目使用
npm install highcharts --save
让我们看看 highcharts 的使用方法,传送门
Highcharts.chart(targetTag, option)
重启项目,建立chart.vue文件
1 <template> 2 <div class="x-bar"> 3 <p :id="id" :option="option"></p> 4 </div> 5 </template> 6 <script> 7 import HighCharts from 'highcharts' 8 export default { 9 data() { 10 return {} 11 }, 12 // 验证类型 13 props: { 14 id: { 15 type: String 16 }, 17 option: { 18 default() { 19 return {} 20 } 21 } 22 }, 23 mounted() { 24 this.hChart = HighCharts // 这个this.hChart是便于每次组件chart的时候都是一个新的chart 25 this.checkAndSetOption() 26 }, 27 watch: { 28 29 }, 30 methods: { 31 checkAndSetOption() { 32 let option = this.option 33 let id = this.id 34 if(this.isValidOption(option)) { 35 // this.hChart.setOption(option) 36 this.hChart.chart(id,option) 37 }else{ 38 console.error("chart option ERROR") 39 } 40 }, 41 isValidOption(option) { 42 return this.isObject(option) && !this.isEmptyObject(option) 43 && this.hasSeriesKey(option) 44 && this.isSeriesArray(option) && !this.isSeriesEmpty(option) 45 }, 46 isObject(option) { 47 return Object.prototype.isPrototypeOf(option) 48 }, 49 isEmptyObject(option) { 50 return Object.keys(option).length === 0 51 }, 52 hasSeriesKey(option) { 53 return !!option['series'] 54 }, 55 isSeriesArray(option) { 56 return Array.isArray(option['series']) 57 }, 58 isSeriesEmpty(option) { 59 return option['series'].length === 0 60 } 61 } 62 } 63 </script>
调用 chart 组件
<template> <div id="appDiv"> <x-chart :id="id1" :option="options"></x-chart> </div> </div> </template> <script> import XChart from '@/components/base/chart/chart import chartOptions from '@/components/base/chart/chart-options' export default { name: 'chart', data() { let options = chartOptions.bar return { id1: 'test', options: options } }, components: { XChart } } </script> <style> #test { width: 400px; height: 400px; margin: 40px auto; } </style>
chart-options.js 内容(用于配置 chart 的 options)
module.exports = {
bar: {
chart: {
type:'column'//指定图表的类型,默认是折线图(line)
},
credits: {
enabled:false
},//去掉地址
title: {
text: '我的第一个图表' //指定图表标题
},
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00',
'#24CBE5' ],
xAxis: {
categories: ['1号', '2号', '3号','3号','3号'] //指定x轴分组
},
yAxis: {
title: {
text: '最近七天', //指定y轴的标题
},
},
plotOptions: {
column: {
colorByPoint:true
},
},
series: [{ //指定数据列
name: '小明',
data: [{
y:1000,
color:"red"}, 5000, 4000,5000,2000] //数据
}]
}
}