Skip to content
ReferenceVersion 6.0.2

RChart and useChart ​

RChart takes ECharts options and manages the instance, theme changes, resize observation, and cleanup. Give the container a definite height. height="100%" depends on the parent's height. The page owns chart data and series configuration.

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

export default defineComponent({
  setup() {
    const [register] = useChart()
    return () => (
      <RChart
        onRegister={register}
        preset="card"
        title="Orders this week"
        height={300}
        options={{
          xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
          yAxis: { type: 'value' },
          series: [{ type: 'bar', data: [12, 19, 14] }],
        }}
      />
    )
  },
})

Interactive example ​

View example source
tsx
import DemoPage from '../components/DemoPage'
import DemoResult from '../components/DemoResult'
import './index.scss'
import { getDemoCharts } from '@/api/demo/data'
import type { DemoCharts } from '@/api/demo/data'
import { useI18n } from '@/hooks'
import { RChart, useChart } from '@ray-template/ui/chart'
import { NButton, NCard, NFlex, NSwitch } from 'naive-ui'

const Echart = defineComponent({
  name: 'REchart',
  setup() {
    const [register, { dispose, render }] = useChart()
    const [register2, { dispose: dispose2, render: render2 }] = useChart()
    const { t } = useI18n('demoDetails.chart')
    const chartData = shallowRef<DemoCharts>()
    const requestController = new AbortController()

    onScopeDispose(() => requestController.abort())

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

    const baseOptions = computed<GlobalEChartsCoreOption>(() => ({
      legend: { type: 'scroll', top: 0 },
      tooltip: { trigger: 'axis' },
      grid: { left: 44, right: 14, top: 42, bottom: 26 },
      xAxis: {
        type: 'category',
        data: chartData.value?.days ?? [],
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: t('orders'),
          data: chartData.value?.orders ?? [],
          type: 'bar',
          barMaxWidth: 24,
        },
        {
          name: t('visits'),
          data: chartData.value?.visits ?? [],
          type: 'bar',
          barMaxWidth: 24,
        },
      ],
    }))
    const pieOptions = computed<GlobalEChartsCoreOption>(() => ({
      tooltip: { trigger: 'item' },
      legend: { type: 'scroll', bottom: 0 },
      series: [
        {
          type: 'pie',
          radius: ['40%', '68%'],
          center: ['50%', '46%'],
          label: { show: false },
          data: (chartData.value?.sources ?? []).map(({ key, value }) => ({
            value,
            name: t(key),
          })),
        },
      ],
    }))
    const baseLineOptions = computed(() => ({
      tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
      legend: { type: 'scroll', bottom: 0 },
      grid: { left: 52, right: 20, top: 20, bottom: 58 },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: chartData.value?.days ?? [],
        },
      ],
      yAxis: [{ type: 'value' }],
      series: (chartData.value?.lines ?? []).map((line) => ({
        name: line.name,
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: { focus: 'series' },
        data: line.values,
      })),
    }))

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

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

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

    const loadCharts = async (refresh = false) => {
      state.loading1 = true

      try {
        chartData.value = await getDemoCharts(refresh, requestController.signal)

        if (refresh) state.revision += 1
      } catch {
        if (!requestController.signal.aborted)
          window.$message.error(t('loadFailed'))
      } finally {
        state.loading1 = false
      }
    }

    void loadCharts()
    const updateChartOptions = () => {
      void loadCharts(true)
    }

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

    return (
      <DemoPage
        title={this.$t('menu.Echart')}
        description={this.$t('showcase.chartDescription')}
        eyebrow="RAY TEMPLATE / EXAMPLES"
      >
        <div class="echart">
          <section class="echart__lead">
            <NFlex align="center">
              <NButton
                disabled={!this.lineReady || 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}
                onSuccess={() => {
                  this.lineReady = true
                  this.lineVisible = true
                }}
                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>
          </section>
          <div class="echart__examples">
            <NCard title={this.$t('demoDetails.chart.fixedTheme')}>
              <NFlex vertical>
                <NFlex>
                  <NButton
                    disabled={!this.barReady || this.barVisible}
                    onClick={render2}
                  >
                    {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}
                    onSuccess={() => {
                      this.barReady = true
                      this.barVisible = true
                    }}
                    theme="ray-naive"
                    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.pieOptions} />
              </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>
        </div>
      </DemoPage>
    )
  },
})

export default Echart

Rendering, themes, and updates ​

PropDefaultDescription
options{}ECharts options. showAria defaults to false. The component controls aria.enabled and aria.decal.show and preserves other ARIA settings.
width / height'100%'CSS dimensions. Numbers are pixels.
use[]Extra ECharts registrations. The built-in registrar covers bar, line, pie, candlestick, scatter, and pictorial bar series, the Canvas renderer, and base modules such as titles, tooltips, grids, datasets, and legends.
intersectionObservertrueInitializes when the target intersects. Hidden charts may have no instance yet. Starts immediately in browsers without intersection observation.
intersectionObserverTarget / intersectionOptionsContainer / { threshold: 0.1 }Custom observation target and options.
autoResize / autoResizeObserverTargettrue / chart containerThrottles resize on container size changes.
watchOptions / watchDeeptrue / trueWatch options and choose deep observation.
watchOptionsThrottleWait500Options update throttle interval in milliseconds.
nextTicktrueAwait the Vue update before initialization.
setChartOptions{ notMerge: true, lazyUpdate: true, silent: false, replaceMerge: [] }ECharts setOption controls.
theme / autoChangeThemenull / trueFollow the app's four styles and color mode. Pass a registered name for a fixed theme.
loading / loadingOptionsfalse / current chart themeShow the ECharts loading mask and override selected default styles.

The default is ray-modern, ray-naive, ray-material, or ray-plain, with a -dark variant for each. theme="default" uses the built-in ECharts theme and follows app color mode when autoChangeTheme=true. Another explicit registered theme stays fixed. Set autoChangeTheme=false to disable automatic dark variant selection. The older macarons and macarons-dark themes have been removed.

The eight themes coordinate canvas, text, legend, axes, tooltips, and series colors with the corresponding card surfaces. Modern uses cool tones, Naive starts with green, Material uses purple and soft tones, and Plain uses a subdued categorical palette. Changing the application primary color leaves chart series colors intact. Explicit page options take precedence.

The default loading mask uses the chart palette. Transparent or invalid backgrounds in custom themes fall back to the corresponding light or dark surface to avoid a black mask. Use loadingOptions to override the mask, text, or spinner.

Theme switching calls ECharts 6 setTheme, keeping the instance and listeners. ECharts rebuilds its option model and can reset legend selection, zoom, and incremental options set in merge mode. Supply the complete options to retain these values.

Card preset and callbacks ​

  • preset="card" uses Naive UI Card and supports title (string or render function), bordered (default true), and contentStyle. Replace the upper-right content with cardExtra.
  • The default menu includes image download. downloadOptions accepts ECharts getDataURL options and an optional filename. dropdownOptions replaces the menu and onDropdownSelect(key, option) reports the selection.
  • Initialization success calls onRegister(instance, render, dispose), onSuccess(instance), and onFinally() in order. Failure disposes the instance, calls onError() and onFinally(), and reports through Vue error handling. The initial options render synchronously so the registration callback can read the chart. Later updates follow setChartOptions.

useChart() returns [register, actions]. getChartInstance() returns { echartInst, render, dispose } and throws before registration. isDisposed() checks the underlying instance. dispose() releases it and stops observation. render() mounts it again. Update an existing chart through options or setOption. Unmounting cleans up the chart.

Props · Implementation · useChart