跳转到正文

RChart 与 useChart ​

RChart 接收 ECharts options,负责创建实例、更新主题、监听尺寸与清理。需要确定的容器高度;height="100%" 依赖父元素的高度。图表数据和 series 配置由页面管理。

tsx
import { RChart, useChart } from '@/components'
import { defineComponent } from 'vue'

export default defineComponent({
  setup() {
    const [register] = useChart()
    return () => (
      <RChart
        onRegister={register}
        preset="card"
        title="周订单量"
        height={300}
        options={{
          xAxis: { type: 'category', data: ['周一', '周二', '周三'] },
          yAxis: { type: 'value' },
          series: [{ type: 'bar', data: [12, 19, 14] }],
        }}
      />
    )
  },
})

交互示例 ​

查看示例源码
tsx
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
import './index.scss'
import { RChart, useChart } from '@/components'
import type { RChartType } from '@/components'
import { NButton, NCard, NFlex, NSwitch } from 'naive-ui'

const Echart = defineComponent({
  name: 'REchart',
  setup() {
    const [register, { getChartInstance, dispose, render, isDisposed }] =
      useChart()
    const [
      register2,
      {
        getChartInstance: getChartInstance2,
        dispose: dispose2,
        render: render2,
        isDisposed: isDisposed2,
      },
    ] = useChart()

    const chartLoading = ref(false)
    const chartAria = ref(false)
    const state = reactive({
      loading: false,
      loading1: false,
      lineVisible: true,
      barVisible: true,
      revision: 1,
    })

    const baseOptions: GlobalEChartsCoreOption = {
      legend: {},
      tooltip: {},
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '日期',
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)',
          },
        },
        {
          name: '数量',
          data: [12, 220, 250, 180, 20, 10, 190],
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)',
          },
        },
      ],
    }
    const basePieOptions: GlobalEChartsCoreOption = {
      title: {
        text: 'Referer of a Website',
        subtext: 'Fake Data',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '50%',
          data: [
            {
              value: 1048,
              name: 'Search Engine',
            },
            {
              value: 735,
              name: 'Direct',
            },
            {
              value: 580,
              name: 'Email',
            },
            {
              value: 484,
              name: 'Union Ads',
            },
            {
              value: 300,
              name: 'Video Ads',
            },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    }
    const baseLineOptions = ref({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985',
          },
        },
      },
      legend: {
        data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine'],
      },
      grid: {
        left: '4%',
        right: '4%',
        top: '2%',
        outerBounds: {
          bottom: '10%',
        },
        outerBoundsMode: 'auto',
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: 'Email',
          type: 'line',
          stack: 'Total',
          areaStyle: {},
          emphasis: {
            focus: 'series',
          },
          data: [120, 132, 101, 134, 90, 230, 210],
        },
        {
          name: 'Union Ads',
          type: 'line',
          stack: 'Total',
          areaStyle: {},
          emphasis: {
            focus: 'series',
          },
          data: [220, 182, 191, 234, 290, 330, 310],
        },
        {
          name: 'Video Ads',
          type: 'line',
          stack: 'Total',
          areaStyle: {},
          emphasis: {
            focus: 'series',
          },
          data: [150, 232, 201, 154, 190, 330, 410],
        },
        {
          name: 'Direct',
          type: 'line',
          stack: 'Total',
          areaStyle: {},
          emphasis: {
            focus: 'series',
          },
          data: [320, 332, 301, 334, 390, 330, 320],
        },
        {
          name: 'Search Engine',
          type: 'line',
          stack: 'Total',
          label: {
            show: true,
            position: 'top',
          },
          areaStyle: {},
          emphasis: {
            focus: 'series',
          },
          data: [820, 932, 901, 934, 1290, 1330, 1320],
        },
      ],
    })

    const handleLoadingShow = (bool: boolean) => {
      state.loading = bool
    }

    const handleAriaShow = (bool: boolean) => {
      chartAria.value = bool
    }

    const mountChart = () => {
      if (isDisposed()) {
        render()
        state.lineVisible = true
      } else {
        window.$message.warning('图表已渲染~')
      }
    }

    const unmountChart = () => {
      dispose()
      state.lineVisible = false
    }

    const updateChartOptions = () => {
      state.loading1 = true

      const createData = () => Math.floor((Math.random() + 1) * 100)

      setTimeout(() => {
        baseLineOptions.value.series[0].data = new Array(7)
          .fill(0)
          .map(() => createData())
        baseLineOptions.value.series[1].data = new Array(7)
          .fill(0)
          .map(() => createData())

        state.loading1 = false
        state.revision += 1
      }, 1000)
    }

    return {
      baseOptions,
      chartLoading,
      handleLoadingShow,
      chartAria,
      handleAriaShow,
      basePieOptions,
      baseLineOptions,
      ...toRefs(state),
      mountChart,
      unmountChart,
      updateChartOptions,
      register,
      register2,
      dispose2,
      render2,
      isDisposed2,
    }
  },
  render() {
    const { register, register2, dispose2, render2, isDisposed2, loading1 } =
      this

    return (
      <DemoPage
        title={this.$t('menu.Echart')}
        description={this.$t('showcase.chartDescription')}
        eyebrow="RAY TEMPLATE / EXAMPLES"
      >
        <div class="echart">
          <NCard title={this.$t('demoDetails.chart.sales')}>
            <NFlex style={['padding: 18px 0']}>
              <NButton disabled={this.lineVisible} onClick={this.mountChart}>
                {this.$t('demoDetails.chart.mount')}
              </NButton>
              <NButton disabled={!this.lineVisible} onClick={this.unmountChart}>
                {this.$t('demoDetails.chart.dispose')}
              </NButton>
              <NButton
                disabled={!this.lineVisible || loading1}
                onClick={this.updateChartOptions}
              >
                {this.$t('demoDetails.chart.update')}
              </NButton>
              <NButton
                onClick={() => {
                  this.loading1 = !this.loading1
                }}
              >
                {this.$t(
                  loading1
                    ? 'demoDetails.chart.stopLoading'
                    : 'demoDetails.chart.showLoading',
                )}
              </NButton>
            </NFlex>
            <div class="chart--container">
              <RChart
                onRegister={register}
                title={this.$t('demoDetails.chart.sales')}
                autoChangeTheme
                options={this.baseLineOptions}
                showAria={this.chartAria}
                preset="card"
                loading={loading1}
              />
            </div>
            <DemoResult label={this.$t('demoDetails.chart.series')}>
              {this.lineVisible
                ? this.$t('demoDetails.chart.revision', {
                    value: this.revision,
                  })
                : this.$t('demoDetails.chart.unmounted')}
            </DemoResult>
          </NCard>
          <NCard title={this.$t('demoDetails.chart.fixedTheme')}>
            <NFlex vertical>
              <NFlex>
                <NButton
                  onClick={() => {
                    if (isDisposed2()) {
                      render2()
                      this.barVisible = true
                    } else {
                      window.$message.warning('不可以重复渲染图表~')
                    }
                  }}
                >
                  {this.$t('demoDetails.chart.mount')}
                </NButton>
                <NButton
                  disabled={!this.barVisible}
                  onClick={() => {
                    dispose2()
                    this.barVisible = false
                  }}
                >
                  {this.$t('demoDetails.chart.dispose')}
                </NButton>
              </NFlex>
              <div class="chart--container">
                <RChart
                  onRegister={register2}
                  autoChangeTheme={false}
                  theme="default"
                  options={this.baseOptions}
                />
              </div>
            </NFlex>
          </NCard>
          <NCard title={this.$t('demoDetails.chart.showLoading')}>
            <NSwitch
              v-model:value={this.chartLoading}
              onUpdateValue={this.handleLoadingShow.bind(this)}
              style={['padding: 18px 0']}
            >
              {{
                checked: () => this.$t('demoDetails.chart.stopLoading'),
                unchecked: () => this.$t('demoDetails.chart.showLoading'),
              }}
            </NSwitch>
            <div class="chart--container">
              <RChart loading={this.loading} options={this.baseOptions} />
            </div>
          </NCard>
          <NCard title={this.$t('demoDetails.chart.pattern')}>
            <NSwitch
              v-model:value={this.chartAria}
              onUpdateValue={this.handleAriaShow.bind(this)}
              style={['padding: 18px 0']}
            >
              {{
                checked: () => this.$t('demoDetails.chart.hidePattern'),
                unchecked: () => this.$t('demoDetails.chart.pattern'),
              }}
            </NSwitch>
            <div class="chart--container">
              <RChart options={this.baseOptions} showAria={this.chartAria} />
            </div>
          </NCard>
        </div>
      </DemoPage>
    )
  },
})

export default Echart

渲染、主题与更新 ​

属性默认说明
options{}ECharts 配置。showAria 默认 false,模板会写入 aria.enabled 和 aria.decal.show。
width / height'100%'CSS 尺寸,数字按像素。
use[]额外 ECharts 注册项。内置柱、线、饼、K 线、散点、象形柱、Canvas,以及标题、提示、网格、数据集、图例等基础模块。
intersectionObservertrue进入观察范围后挂载图表;隐藏区域的实例可能尚不可用。
intersectionObserverTarget / intersectionOptions容器 / { threshold: 0.1 }自定义观察目标与参数。
autoResize / autoResizeObserverTargettrue / 外层容器容器尺寸变化后节流 resize。
watchOptions / watchDeeptrue / true是否订阅 options,是否深层观察。
watchOptionsThrottleWait500options 更新节流间隔(毫秒)。
nextTicktrue初始化前等待 Vue 更新。
setChartOptions{ notMerge: true, lazyUpdate: true, silent: false, replaceMerge: [] }ECharts setOption 的控制参数。
theme / autoChangeThemenull / true默认用应用的 ECharts 主题及暗色变体。固定主题请传注册后的主题名。
loading / loadingOptionsfalse / 模板加载样式是否显示 ECharts 加载层及参数。

Provider 指定主题时优先。当前实现中 theme="default" 在 autoChangeTheme=true 时会传内建 dark,设为 false 才使用空主题名;需要明确的渲染效果时建议传实际主题名。切换主题可能重建实例,持有实例引用的代码应重新读取或注册。

卡片预设和回调 ​

  • preset="card" 使用 Naive UI Card,支持 title(字符串或渲染函数)、bordered(默认 true)、contentStyle。cardExtra 插槽可替换右上角。
  • 默认菜单含图片下载;downloadOptions 接受 ECharts getDataURL 参数和可选 filename。传入 dropdownOptions 会替换菜单,选择项通过 onDropdownSelect(key, option) 通知。
  • onSuccess(instance)、onError()、onFinally() 对应初始化结果;错误仍可能向调用侧抛出。onRegister(instance, render, dispose) 在可用实例建立后调用。

useChart() 返回 [register, actions]。getChartInstance() 返回 { echartInst, render, dispose },注册前会抛错。isDisposed() 检查底层实例,dispose() 释放图表和监听,render() 调用组件挂载逻辑;已存在实例时不要用它替代更新 options 或 setOption。图表随组件卸载清理。

Props · 组件实现 · useChart