• vue3 tsx 项目中使用 Antv/G2 实现多线折线图


    Antv/G2 文档
    Antv/G2 双折线图

    安装 antV-G2

    通过 npm 安装

    项目中安装 antv/g2 依赖库

    npm install @antv/g2 --save
    
    • 1

    安装成功:
    在这里插入图片描述

    浏览器引入

    可以将脚本下载到本地,也可以直接引入在线资源。

    引入在线资源

    <!-- 引入在线资源,选择需要的 g2 版本以替换 version 变量 -->
    <script src="https://gw.alipayobjects.com/os/lib/antv/g2/{{version}}/dist/g2.min.js"></script>
    <!-- 浏览器引入,请使用全局命名空间 G2,如 new Chart() 改为 new G2.Chart,即可运行。 -->
    
    • 1
    • 2
    • 3

    引入本地脚本

    <!-- 引入本地脚本 -->
    <script src="./g2.js"></script>
    
    • 1
    • 2

    使用 script 标签引入 G2 资源时,挂载在 window 上的变量名为 G2。所以,实例中需要加上 G2 的前缀。如下:

    const chart = new G2.Chart({
    })
    
    • 1
    • 2

    项目使用

    新建文件 IndicatorTrend.tsx

    import { defineComponent, PropType, onMounted, ref } from 'vue'
    import { useChartAutoResize } from '@/hooks/chart'
    import styled from '@/styled-components'
    import { Chart } from '@antv/g2';
    
    export interface TrendListItem {
      date: string
      city: string
      tempvalue: number
    }
    
    interface Props {
      dataList?: TrendListItem[]
    }
    
    const Container = styled.div`  
      width: 100%;
      height: 100%;
    `
    
    const TitleBox = styled.h3`
      margin-bottom: 10px;
    `
    
    const ChartContainer = styled.div`
      height:100%;
    `
    
    export default defineComponent({
      props: {
        dataList: {
          type: Array as PropType<TrendListItem[]>,
          default: () => []
        }
      },
      setup() {
        const dataList = ref<TrendListItem[]>([])
        const canvasRef = ref<null | HTMLElement>(null)
        const chartRef = ref<null | InstanceType<typeof Chart>>(null)
    
        onMounted(() => {
          if (canvasRef.value) {
            const chart = new Chart({
              container: canvasRef.value,
              autoFit: true
            })
    
            chartRef.value = chart
          }
    
          refreshChartView()
        })
    
        useChartAutoResize(canvasRef, chartRef)
    
        function refreshChartView(){      
          const chart: any = chartRef.value
          chart.clear()
          setTimeout(() => {
            chart.data(dataList.value)
            
            chart.scale({
              date: {
                range: [0, 1],
              },
              tempvalue: {
                nice: true,
              },
            });
            
            chart.tooltip({
              showCrosshairs: true,
              shared: true,
            });
            
            chart.axis('tempvalue', {
              label: {
                formatter: (val:number) => {
                  return val + ' °C';
                },
              },
            });
            
            chart
              .line()
              .position('date*tempvalue')
              .color('city')
              .shape('smooth');
            
            chart
              .point()
              .position('date*tempvalue')
              .color('city')
              .shape('circle')
              .style({
                stroke: '#fff',
                lineWidth: 1,
              });
            
            chart.render()
          })
        }
    
        return (props: Props) => {
          dataList.value = props.dataList || []
          return (
            <Container>
              <TitleBox>总趋势</TitleBox> 
              <ChartContainer>      
              <div ref={canvasRef} />     
              </ChartContainer>   
            </Container>
          )
        }
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116

    其中,引用了公共方法 hooks/chart

    import { ref, onUnmounted, watchEffect } from 'vue'
    import { changeSizeAfterCanvasResize, deleteGlobalChartItem } from '@/utils/chart'
    
    // 没找到ref的类型
    export const useChartAutoResize = (canvasRef: any, chartRef: any): void => {
      const queueIndex = ref<number>(-1)
      const isCreated = ref(false)
    
      function clearThisChart() {
        queueIndex.value > 0 && deleteGlobalChartItem(queueIndex.value)
      }
    
      // 后续如果需要重复绑定,可以返回一个更新的方法
      watchEffect(() => {
        if (!isCreated.value && canvasRef.value && chartRef.value) {
          clearThisChart()
          isCreated.value = true
          queueIndex.value = changeSizeAfterCanvasResize(canvasRef.value, chartRef.value)
        }
      }, {
        flush: 'post'
      })
    
      onUnmounted(() => {
        clearThisChart()
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    utils/chart 文件:

    import { Chart } from '@antv/g2'
    import { ChartResizeQueueItem } from '@/globalType'
    
    const getChartIndex: () => number = createChartIndex()
    
    export function getGlobalChartQueue(): ChartResizeQueueItem[] {
      return window.chartResizeQueue
    }
    
    export function setGlobalChartQueue(arr: ChartResizeQueueItem[]): ChartResizeQueueItem[] {
      window.chartResizeQueue = arr
      return window.chartResizeQueue
    }
    
    export function deleteGlobalChartItem(index: number): void {
      const queue = getGlobalChartQueue()
      setGlobalChartQueue(queue.filter(item => item.index !== index))
    }
    
    // canvas适应父元素的大小,并刷新图表宽高
    export function refreshChartSize(canvas: HTMLElement, chart: Chart): void {
      let width: number = 0
      let height: number = 0
    
      if (canvas.parentNode && getComputedStyle) {
        const styles = getComputedStyle(canvas.parentNode as HTMLElement)
        width = Number(styles.width.split('px')[0])
        height = Number(styles.height.split('px')[0])
      } else if (canvas.parentNode) {
        width = (canvas.parentNode as HTMLElement).offsetWidth
        height = (canvas.parentNode as HTMLElement).offsetHeight
      }
    
      canvas.setAttribute('width', `${width}px`)
      canvas.setAttribute('height', `${height}px`)
      chart.changeSize(width, height)
    }
    
    // 添加到全局图表队列,并且自动更新宽高
    export function changeSizeAfterCanvasResize(canvas: HTMLElement, chart: InstanceType<typeof Chart>): number {
      const queue = getGlobalChartQueue()
      const index: number = getChartIndex()
    
      refreshChartSize(canvas, chart)
      setGlobalChartQueue(queue.concat([{ index, canvas, chart }]))
    
      return index
    }
    
    function createChartIndex() {
      let index: number = 0
    
      return (): number => {
        index++
        return index
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    globalType.ts 文件:

    export interface ChartResizeQueueItem {
      index: number
      canvas: HTMLElement,
      chart: any
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在父组件中引用 IndicatorTrend.tsx 组件:

    <IndicatorTrend dataList={totalTrendList.value}></IndicatorTrend>         
    
    • 1

    数据源为:

    totalTrendList.value = [{
            date: '2023/8/1',
            city: 'bily',
            tempvalue: 4623
          }, {
            date: '2023/8/1',
            city: 'cily',
            tempvalue: 2208
          }, {
            date: '2023/8/1',
            city: 'bill',
            tempvalue: 182
          }, {
            date: '2023/8/2',
            city: 'bily',
            tempvalue: 6145
          }, {
            date: '2023/8/2',
            city: 'cily',
            tempvalue: 2016
          }, {
            date: '2023/8/2',
            city: 'bill',
            tempvalue: 257
          }, {
            date: '2023/8/3',
            city: 'bily',
          
            tempvalue: 508
          }, {
            date: '2023/8/3',
            city: 'cily',
            tempvalue: 2916
          }, {
            date: '2023/8/3',
            city: 'bill',
            tempvalue: 289
          }, {
          
            date: '2023/8/4',
            city: 'bily',
            tempvalue: 6268
          }, {
            date: '2023/8/4',
            city: 'cily',
            tempvalue: 4512
          }, {
            date: '2023/8/4',
            city: 'bill',
            tempvalue: 428
          }, {
            date: '2023/8/5',
            city: 'bily',
            tempvalue: 6411
          }, {
            date: '2023/8/5',
            city: 'cily',
            tempvalue: 8281
          }, {
            date: '2023/8/5',
            city: 'bill',
            tempvalue: 619
          }, {
            date: '2023/8/6',
            city: 'bily',
            tempvalue: 1890
          }, {
          
            date: '2023/8/6',
            city: 'cily',
            tempvalue: 2008
          }, {
            date: '2023/8/6',
            city: 'bill',
            tempvalue: 87
          }, {
            date: '2023/8/7',
            city: 'bily',
            tempvalue: 4251
          }, {
            date: '2023/8/7',
            city: 'cily',
            tempvalue: 1963
          }, {
            date: '2023/8/7',
            city: 'bill',
            tempvalue: 706
          }, {
            date: '2023/8/8',
            city: 'bily',
            tempvalue: 2978
          }, {
            date: '2023/8/8',
            city: 'cily',
            tempvalue: 2367
          }, {
          
            date: '2023/8/8',
            city: 'bill',
            tempvalue: 387
          }, {
            date: '2023/8/9',
            city: 'bily',
            tempvalue: 3880
          }, {
            date: '2023/8/9',
            city: 'cily',
            tempvalue: 2956
          }, {
            date: '2023/8/9',
            city: 'bill',
            tempvalue: 488
          }, {
            date: '2023/8/10',
            city: 'bily',
          
            tempvalue: 3606
          }, {
            date: '2023/8/10',
            city: 'cily',
            tempvalue: 678
          }, {
            date: '2023/8/10',
            city: 'bill',
            tempvalue: 507
          }, {
          
            date: '2023/8/11',
            city: 'bily',
            tempvalue: 4311
          }, {
            date: '2023/8/11',
            city: 'cily',
            tempvalue: 3188
          }, {
            date: '2023/8/11',
            city: 'bill',
            tempvalue: 548
          }, {
            date: '2023/8/12',
            city: 'bily',
            tempvalue: 4116
          }, {
            date: '2023/8/12',
            city: 'cily',
            tempvalue: 3491
          }, {
            date: '2023/8/12',
            city: 'bill',
            tempvalue: 456
          }, {
            date: '2023/8/13',
            city: 'bily',
            tempvalue: 6419
          }, {
          
            date: '2023/8/13',
            city: 'cily',
            tempvalue: 2852
          }, {
            date: '2023/8/13',
            city: 'bill',
            tempvalue: 689
          }, {
            date: '2023/8/14',
          
            city: 'bily',
            tempvalue: 1643
          }, {
            date: '2023/8/14',
            city: 'cily',
            tempvalue: 4788
          }, {
            date: '2023/8/14',
            city: 'bill',
            tempvalue: 280
          }, {
            date: '2023/8/15',
            city: 'bily',
            tempvalue: 445
          }, {
            date: '2023/8/15',
            city: 'cily',
            tempvalue: 4319
          }, {
          
            date: '2023/8/15',
            city: 'bill',
            tempvalue: 176
          }]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190

    页面效果:
    在这里插入图片描述

  • 相关阅读:
    K8S:Yaml文件详解及编写示例
    当Number类型的id超过16位时,JavaScript的数据处理和储存问题
    [后端]Mybatis 使用注解进行模糊查询报错
    WordPress是什么?我也想用 WordPress~
    我用Devchat开发了公务员报名确认系统自动登录脚本,再也不用担心挤不进去了
    基于大仓库的微服务差异化构建工具
    PMP有没有必要续证?
    mac 配置iTerm2和oh-my-zsh主题
    pytorch初学笔记(十三):神经网络基本结构之Sequential层的使用以及搭建完整的小型神经网络实战
    2023年【危险化学品生产单位主要负责人】试题及解析及危险化学品生产单位主要负责人模拟试题
  • 原文地址:https://blog.csdn.net/HH18700418030/article/details/132103127