先来介绍一下 highchart 图表吧, 它其实和 charts 很相似, 但又比 charts 多了许多功能, 最近做的项目我发现好多图都是 charts 图表实现不了的, 就认真研究了一下 highchart, 前天搞了一下午没搞出来, 昨天上午过来灵机一动居然出来了. 下面来说一下步骤吧
1. 安装 highcharts:
npm install highcharts --save
2. 新建一个 comp.vue 的文件
<script>
import HighCharts from 'highcharts'
export default {
// 验证类型
props: {
id: {
type: String
},
option: {
type: Object
}
},
mounted() {
HighCharts.chart(this.id, this.option)
}
}
</script>
3. 把 comp.vue 引入你所需要的文件中,(别忘了注册组件哦)
- import XChart from './comp.vue'
- components: {
- XChart
- },
4. 在需要图表的地方 (这里注意一下 v-if)
this.showchart 是一个变量, 定义在 data 里
5. 在 data 里边定义
- showchart:false,
- option: {
- title:null,
- tooltip: {
headerFormat: '币种成交额占比
- ',
- pointFormat: '{point.name}: {point.percentage:.1f}%'
- },
- plotOptions: {
- pie: {
- allowPointSelect: true,
- cursor: 'pointer',
- dataLabels: {
- enabled: false
- },
- showInLegend: true // 设置饼图是否在图例中显示
- }
- },
- series: [{
- type: 'pie',
- data:[],
- }]
- }
6. 重点来了, 我主要想说一下异步获取数据, 但是获取到的数据不显示的问题, 我这里用的是 feach 获取的数据, 根据需求也可以用 ajax 来获取. 想必这个肯定都知道, 我就不多说了, data 是数组对象格式的,
- fetch(this.HOST+"/exchanges/historical-statisticseid="+this.eid).then(e=>{
- return e.json();
- }).then(e=>{
- for(var i=0;i<1;i++){
- this.option.series[0].data=new Array();
- for(var j=0;j
注意
name:`${e.data[j].symbol} ${e.data[j].proportion}%` // 是为了让图例中显示百分比
7. 做到这儿你会发现数据格式完全正确但是就是显示不出来, 把数据直接放到 data 里面是完全没问题的, 这就是我纠结了一下午的问题, 尝试了各种方法都不行, 它是一个异步问题, 所以这个时候就需要用到 v-if 了, 等有了数据再渲染. 开始的时候让 this.showchart=false, 图表不渲染, 当 this.option.series[0].data 有数据之后让 this.showchart =true, 图表中用 v-if 控制, 注意一定要用 v-if,v-show 是不行的. 哈哈, 记得他俩的区别还是当时在一起的时候他再三叮嘱我的, 可算是没忘了.
this.showchart=true
好了, 这样图就可以出来了.
来源: https://www.2cto.com/kf/201807/760180.html