最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue3封裝echarts組件最佳形式詳解

 更新時(shí)間:2022年11月16日 09:20:41   作者:遠(yuǎn)山無(wú)期  
這篇文章主要為大家介紹了vue3封裝echarts組件最佳形式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

思路

項(xiàng)目中經(jīng)常用到echarts,不做封裝直接拿來(lái)使用也行,但不可避免要寫(xiě)很多重復(fù)的配置代碼,封裝稍不注意又會(huì)過(guò)度封裝,丟失了擴(kuò)展性和可讀性。始終沒(méi)有找到一個(gè)好的實(shí)踐,偶然看到一篇文章,給了靈感。找到了一個(gè)目前認(rèn)為用起來(lái)很舒服的封裝。

  • 結(jié)合項(xiàng)目需求,針對(duì)不同類型的圖表,配置基礎(chǔ)的默認(rèn)通用配置,例如x/y,label,圖例等的樣式
  • 創(chuàng)建圖表組件實(shí)例(不要使用id,容易重復(fù),還需要操作dom,直接用ref獲取當(dāng)前組件的el來(lái)創(chuàng)建圖表),提供type(圖表類型),和options(圖表配置)兩個(gè)必要屬性
  • 根據(jù)傳入type,加載默認(rèn)的圖表配置
  • 深度監(jiān)聽(tīng)傳入的options,變化時(shí)更新覆蓋默認(rèn)配置,更新圖表

注意要確保所有傳入圖表組件的options數(shù)組都是shallowReactive類型,避免數(shù)組量過(guò)大,深度響應(yīng)式導(dǎo)致性能問(wèn)題

目錄結(jié)構(gòu)

├─v-charts
│  │  index.ts     // 導(dǎo)出類型定義以及圖表組件方便使用
│  │  type.d.ts    // 各種圖表的類型定義
│  │  useCharts.ts // 圖表hooks
│  │  v-charts.vue // echarts圖表組件
│  │
│  └─options // 圖表配置文件
│          bar.ts
│          gauge.ts
│          pie.ts

組件代碼

v-charts.vue

<template>
  <div class="v-charts" ref="chartRef" />
</template>
<script lang="ts" setup>
import { PropType } from "vue";
import * as echarts from "echarts/core";
import { useCharts, ChartType } from "./useCharts";
defineOptions({
  name: "VCharts"
});
const props = defineProps({
  type: {
    type: String as PropType<ChartType>,
    default: "bar"
  },
  options: {
    type: Object as PropType<echarts.EChartsCoreOption>,
    default: () => ({})
  }
});
const { type, options } = toRefs(props);
const chartRef = shallowRef();
const { charts, setOptions, initChart } = useCharts({ type, el: chartRef });
onMounted(async () => {
  await initChart();
  setOptions(options.value);
});
watch( // 出于性能考慮,所有傳入組件options的數(shù)據(jù)都要是shallowReactive類型,避免不必要的響應(yīng)式轉(zhuǎn)換
  options,
  () => {
    setOptions(options.value);
  },
  {
    deep: true
  }
);
defineExpose({
  $charts: charts
});
</script>
<style lang="scss" scoped>
.v-charts {
  width: 100%;
  height: 100%;
  min-height: 200px;
}
</style>

useCharts.ts

import { ChartType } from "./type";
import * as echarts from "echarts/core";
import { ShallowRef, Ref } from "vue";
import {
  TitleComponent,
  LegendComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from "echarts/components";
import { BarChart, LineChart, PieChart, GaugeChart } from "echarts/charts";
import { LabelLayout, UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
// 異步導(dǎo)入options中的所有默認(rèn)配置項(xiàng)
const optionsModules = import.meta.glob<{ default: echarts.EChartsCoreOption }>("./options/**.ts");
interface ChartHookOption {
  type?: Ref<ChartType>;
  el: ShallowRef<HTMLElement>;
}
/**
 *  視口變化時(shí)echart圖表自適應(yīng)調(diào)整
 */
class ChartsResize {
  #charts = new Set<echarts.ECharts>(); // 緩存已經(jīng)創(chuàng)建的圖表實(shí)例
  #timeId = null;
  constructor() {
    window.addEventListener("resize", this.handleResize.bind(this)); // 視口變化時(shí)調(diào)整圖表
  }
  getCharts() {
    return [...this.#charts];
  }
  handleResize() {
    clearTimeout(this.#timeId);
    this.#timeId = setTimeout(() => {
      this.#charts.forEach(chart => {
        chart.resize();
      });
    }, 500);
  }
  add(chart: echarts.ECharts) {
    this.#charts.add(chart);
  }
  remove(chart: echarts.ECharts) {
    this.#charts.delete(chart);
  }
  removeListener() {
    window.removeEventListener("resize", this.handleResize);
  }
}
export const chartsResize = new ChartsResize();
// 注冊(cè)創(chuàng)建echarts實(shí)例
export const useCharts = ({ type, el }: ChartHookOption) => {
  echarts.use([
    BarChart,
    LineChart,
    BarChart,
    PieChart,
    GaugeChart,
    TitleComponent,
    LegendComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer
  ]);
  const charts = shallowRef<echarts.ECharts>();
  let options!: echarts.EChartsCoreOption;
  //根據(jù)要?jiǎng)?chuàng)建的圖表類型,加載對(duì)應(yīng)的默認(rèn)配置項(xiàng)
  const getOptions = async () => {
    const moduleKey = `./options/${type.value}.ts`;
    const { default: defaultOption } = await optionsModules[moduleKey]();
    return defaultOption;
  };
  //更新圖表
  const setOptions = (opt: echarts.EChartsCoreOption) => {
    charts.value.setOption(opt);
  };
  const initChart = async () => {
    charts.value = echarts.init(el.value);
    options = await getOptions();
    charts.value.setOption(options);
    chartsResize.add(charts.value); // 將圖表實(shí)例添加到緩存中
  };
  onBeforeUnmount(() => {
    chartsResize.remove(charts.value); // 移除緩存
  });
  return {
    charts,
    setOptions,
    initChart
  };
};
export const chartsOptions = <T extends echarts.EChartsCoreOption>(option: T) => shallowReactive<T>(option);
export * from "./type.d";

type.d.ts

/*
 * @Description:
 * @Version: 2.0
 * @Autor: GC
 * @Date: 2022-03-02 10:21:33
 * @LastEditors: GUOCHAO82
 * @LastEditTime: 2022-06-02 17:45:48
 */
// import * as echarts from 'echarts/core';
import * as echarts from 'echarts'
import { XAXisComponentOption, YAXisComponentOption } from 'echarts';
import {
  TitleComponentOption,
  TooltipComponentOption,
  GridComponentOption,
  DatasetComponentOption,
  AriaComponentOption,
  AxisPointerComponentOption,
  LegendComponentOption,
} from 'echarts/components';// 組件
import {
  // 系列類型的定義后綴都為 SeriesOption
  BarSeriesOption,
  LineSeriesOption,
  PieSeriesOption,
  FunnelSeriesOption,
  GaugeSeriesOption
} from 'echarts/charts';
type Options = LineECOption|BarECOption|PieECOption|FunnelOption
type BaseOptionType = XAXisComponentOption|YAXisComponentOption|TitleComponentOption|TooltipComponentOption|LegendComponentOption|GridComponentOption
type BaseOption = echarts.ComposeOption<BaseOptionType>
type LineECOption = echarts.ComposeOption<LineSeriesOption|BaseOptionType>
type BarECOption = echarts.ComposeOption<BarSeriesOption|BaseOptionType>
type PieECOption = echarts.ComposeOption<PieSeriesOption|BaseOptionType>
type FunnelOption = echarts.ComposeOption<FunnelSeriesOption|BaseOptionType>
type GaugeECOption = echarts.ComposeOption<GaugeSeriesOption|GridComponentOption>
type EChartsOption = echarts.EChartsOption;
type ChartType = 'bar'|'line'|'pie' | 'gauge'
export {
    BaseOption,
    ChartType,
    LineECOption, //
    BarECOption,
    Options,
    PieECOption,
    FunnelOption,
    GaugeECOption,
    EChartsOption
}

options/bar.ts

import { BarECOption } from "../type";
const options: BarECOption = {
  legend: {},
  tooltip: {},
  xAxis: {
    type: "category",
    axisLine: {
      lineStyle: {
        // type: "dashed",
        color: "#C8D0D7"
      }
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: "#7D8292"
    }
  },
  yAxis: {
    type: "value",
    min: "dataMin",
    alignTicks: true,
    splitLine: {
      show: true,
      lineStyle: {
        color: "#C8D0D7",
        type: "dashed"
      }
    },
    axisLine: {
      lineStyle: {
        color: "#7D8292"
      }
    }
  },
  grid: {
    left: 60,
    bottom: "8%",
    top: "20%"
  },
  series: [
    {
      type: "bar",
      barWidth: 20,
      itemStyle: {
        color: {
          type: "linear",
          x: 0,
          x2: 0,
          y: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: "#62A5FF" // 0% 處的顏色
            },
            {
              offset: 1,
              color: "#3365FF" // 100% 處的顏色
            }
          ]
        }
      }
      // label: {
      //   show: true,
      //   position: "top"
      // }
    }
  ]
};
export default options;

項(xiàng)目中使用

index.vue

<template>
  <div class="home">
    <section class="bottom">
      <div class="device-statistics chart-box">
        <div class="title">累計(jì)設(shè)備接入統(tǒng)計(jì)</div>
        <v-charts type="bar" :options="statisDeviceAccess" />
      </div>
      <div class="coordinate-statistics chart-box">
        <div class="title">坐標(biāo)數(shù)據(jù)接入統(tǒng)計(jì)</div>
        <v-charts type="bar" :options="statisCoordAccess" />
      </div>
    </section>
  </div>
</template>
<script lang="ts" setup>
import {
  useStatisDeviceByUserObject,
} from "./hooks";
// 設(shè)備分類統(tǒng)計(jì)
const { options: statisDeviceByUserObjectOpts } = useStatisDeviceByUserObject();
</script>

/hooks/useStatisDeviceByUserObject.ts

export const useStatisDeviceByUserObject = () => {
  // 使用chartsOptions確保所有傳入v-charts組件的options數(shù)據(jù)都是## shallowReactive淺層作用形式,避免大量數(shù)據(jù)導(dǎo)致性能問(wèn)題
  const options = chartsOptions<BarECOption>({
    yAxis: {},
    xAxis: {},
    series: []
  });
  const init = async () => {
    const xData = [];
    const sData = [];
    const dicts = useHashMapDics<["dev_user_object"]>(["dev_user_object"]);
    const data = await statisDeviceByUserObject();
    dicts.dictionaryMap.dev_user_object.forEach(({ label, value }) => {
      if (value === "6") return; // 排除其他
      xData.push(label);
      const temp = data.find(({ name }) => name === value);
      sData.push(temp?.qty || 0);
      // 給options賦值時(shí)要注意options是淺層響應(yīng)式
      options.xAxis = { data: xData }; 
      options.series = [{ ...options.series[0], data: sData }];
    });
  };
  onMounted(() => {
    init();
  });
  return {
    options
  };
};

以上就是vue3封裝echarts組件最佳形式詳解的詳細(xì)內(nèi)容,更多關(guān)于vue3封裝echarts組件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • vue+elementUi中的table實(shí)現(xiàn)跨頁(yè)多選功能(示例詳解)

    vue+elementUi中的table實(shí)現(xiàn)跨頁(yè)多選功能(示例詳解)

    最近在開(kāi)發(fā)工業(yè)品超市的后臺(tái)系統(tǒng),遇到一個(gè)需求,就是實(shí)現(xiàn)在一個(gè)table表格中多選數(shù)據(jù),在網(wǎng)上查了好多,有些方法真的是無(wú)語(yǔ),下面通過(guò)本文給大家分享vue+elementUi中的table實(shí)現(xiàn)跨頁(yè)多選功能,感興趣的朋友跟隨小編一起看看吧
    2024-05-05
  • vue-devtools安裝使用全過(guò)程

    vue-devtools安裝使用全過(guò)程

    這篇文章主要介紹了vue-devtools安裝使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • vue中的Object.freeze()?優(yōu)化數(shù)據(jù)方式

    vue中的Object.freeze()?優(yōu)化數(shù)據(jù)方式

    這篇文章主要介紹了vue中的Object.freeze()優(yōu)化數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • Vue中slot插槽作用與原理詳解

    Vue中slot插槽作用與原理詳解

    插槽slot可以說(shuō)在一個(gè)Vue項(xiàng)目里面處處都有它的身影,比如我們使用一些UI組件庫(kù)的時(shí)候,我們通??梢允褂貌宀蹃?lái)自定義我們的內(nèi)容,這篇文章主要介紹了Vue3中slot插槽使用方式,需要的朋友可以參考下
    2022-09-09
  • 解決Vue.js由于延時(shí)顯示了{(lán){message}}引用界面的問(wèn)題

    解決Vue.js由于延時(shí)顯示了{(lán){message}}引用界面的問(wèn)題

    今天小編就為大家分享一篇解決Vue.js由于延時(shí)顯示了{(lán){message}}引用界面的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-08-08
  • vue2.0使用swiper組件實(shí)現(xiàn)輪播效果

    vue2.0使用swiper組件實(shí)現(xiàn)輪播效果

    這篇文章主要為大家詳細(xì)介紹了vue2.0使用swiper組件實(shí)現(xiàn)輪播效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • VUE異步更新DOM - 用$nextTick解決DOM視圖的問(wèn)題

    VUE異步更新DOM - 用$nextTick解決DOM視圖的問(wèn)題

    這篇文章主要介紹了VUE異步更新DOM - 用$nextTick解決DOM視圖的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-11-11
  • vue 導(dǎo)航內(nèi)容設(shè)置選中狀態(tài)樣式的例子

    vue 導(dǎo)航內(nèi)容設(shè)置選中狀態(tài)樣式的例子

    今天小編就為大家分享一篇vue 導(dǎo)航內(nèi)容設(shè)置選中狀態(tài)樣式的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-11-11
  • vue 組件內(nèi)獲取actions的response方式

    vue 組件內(nèi)獲取actions的response方式

    今天小編就為大家分享一篇vue 組件內(nèi)獲取actions的response方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-11-11
  • vue.js中父組件調(diào)用子組件的內(nèi)部方法示例

    vue.js中父組件調(diào)用子組件的內(nèi)部方法示例

    這篇文章主要給大家介紹了關(guān)于vue.js中父組件調(diào)用子組件內(nèi)部方法的相關(guān)資料,文中給出來(lái)了詳細(xì)的示例代碼供大家參考學(xué)習(xí),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10

最新評(píng)論

临武县| 磐安县| 长白| 麻阳| 根河市| 桐乡市| 鞍山市| 游戏| 屏东县| 灵石县| 杭锦旗| 蕉岭县| 太康县| 高阳县| 旬阳县| 增城市| 霍州市| 洛隆县| 吉安市| 黄大仙区| 靖西县| 马边| 连平县| 基隆市| 饶阳县| 通海县| 大田县| 峨眉山市| 福安市| 皮山县| 五河县| 会宁县| 永顺县| 新丰县| 资阳市| 凤冈县| 惠水县| 敖汉旗| 张家口市| 明溪县| 方正县|