antvis / G2

📊 The concise and progressive visualization grammar.
https://g2.antv.antgroup.com
MIT License
12.14k stars 1.59k forks source link

不支持用ref去存储chart实例嘛? #6337

Open Sharang-heng opened 4 months ago

Sharang-heng commented 4 months ago

问题描述

import { onMounted, onUnmounted, ref, watch } from 'vue';
import { Chart } from '@antv/g2';
import { useAppStore } from '@/assets/scripts/stores/app';
import api from '@/assets/scripts/api';
import type { ChartItemData } from '@/assets/scripts/types';
import { useRequest } from 'vue-hooks-plus';

export default defineComponent({
  setup() {
    const chartId = 'age-chart';
    const chart = ref<Chart>(new Chart());
    const colors = [
      '#42cdff',
      '#1ec1b0',
      '#22cc6e',
      '#7638ff',
      '#fda600',
      '#ef3737'
    ];
    const { runAsync, loading } = useRequest(api.getAgeDistUsingGet, {
      manual: true
    });
    const appStore = useAppStore();
  const { appId } = storeToRefs(appStore);
  const stop = watch(
      [appId, chart],
      async ([id, newChart]) => {
        try {
          if (id && newChart) {
            const list= await runAsync({ appId: id });
            chart.value.changeData(list);
            chart.value.render();
          }
        } catch (error) {
          console.log('err', error);
        }
      },
      {
        immediate: true
      }
    );
    onMounted(() => {
      chart.value = new Chart({
        container: chartId,
        height: 300,
        autoFit: true
      });
      chart.value.coordinate({ type: 'polar', innerRadius: 0.4 });
      chart.value
        .interval()
        .encode('x', 'value')
        .encode('y', 'percent')
        .axis(false)
        .encode('color', 'name')
        .scale('color', { range: colors })
        .legend('color', {
          position: 'bottom',
          layout: { justifyContent: 'center' }
        })
        .label({
          position: 'outside',
          text: (data: ChartItemData) => `${(data.percent * 100).toFixed(2)}%`
        })
        .tooltip((data: ChartItemData) => ({
          name: data.name,
          value: data.value,
          title: null
        }))
        .animate('enter', { type: 'waveIn' });
    });
    onUnmounted(() => {
      chart.value.destroy();
      stop();
    });

    return { chart, chartId, loading };
  },
  render() {
    return (
      <a-spin spinning={this.loading}>
        <div id={this.chartId} h-300px>
          {this.chart.value?.data?.length === 0 && (
            <div flex-xy-center>
              <a-empty />
            </div>
          )}
        </div>
      </a-spin>
    );
  }
});

不是很理解为什么会报这两个错 image

重现链接

No response

重现步骤

No response

预期行为

No response

平台

屏幕截图或视频(可选)

No response

补充说明(可选)

No response

pearmini commented 4 months ago

可能是构建相关的问题,可以提供一个复现 demo 吗?