久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      聊聊vue3中echarts用什么形式封裝最好?(代碼詳解)

      項目中經常用到echarts,不做封裝直接拿來使用也行,但不可避免要寫很多重復的配置代碼,封裝稍不注意又會過度封裝,丟失了擴展性和可讀性。始終沒有找到一個好的實踐,偶然看到一篇文章,給了靈感。找到了一個目前認為用起來很舒服的封裝。

      思路

      1. 結合項目需求,針對不同類型的圖表,配置基礎的默認通用配置,例如x/y,label,圖例等的樣式
      2. 創(chuàng)建圖表組件實例(不要使用id,容易重復,還需要操作dom,直接用ref獲取當前組件的el來創(chuàng)建圖表),提供type(圖表類型),和options(圖表配置)兩個必要屬性
      3. 根據(jù)傳入type,加載默認的圖表配置
      4. 深度監(jiān)聽傳入的options,變化時更新覆蓋默認配置,更新圖表
      5. 提供事件支持,支持echart事件按需綁定交互

      注意要確保所有傳入圖表組件的options數(shù)組都是shallowReactive類型,避免數(shù)組量過大,深度響應式導致性能問題

      目錄結構

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


      組件代碼

      v-charts.vue

      <template>   <div ref="chartRef" /> </template> <script setup> import { PropType } from "vue"; import * as echarts from "echarts/core"; import { useCharts, ChartType, ChartsEvents } from "./useCharts";  /**  * echarts事件類型  * 截至目前,vue3類型聲明參數(shù)必須是以下內容之一,暫不支持外部引入類型參數(shù)  * 1. 類型字面量  * 2. 在同一文件中的接口或類型字面量的引用  * // 文檔中有說明:https://cn.vuejs.org/api/sfc-script-setup.html#typescript-only-features  */ interface EventEmitsType {   <T extends ChartsEvents.EventType>(e: `${T}`, event: ChartsEvents.Events[Uncapitalize<T>]): void; }  defineOptions({   name: "VCharts" });  const props = defineProps({   type: {     type: String as PropType<ChartType>,     default: "bar"   },   options: {     type: Object as PropType<echarts.EChartsCoreOption>,     default: () => ({})   } });  // 定義事件,提供ts支持,在組件使用時可獲得友好提示 defineEmits<EventEmitsType>();  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,   () => {     setOptions(options.value);   },   {     deep: true   } ); defineExpose({   $charts: charts }); </script> <style 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";  const optionsModules = import.meta.glob<{ default: echarts.EChartsCoreOption }>("./options/**.ts");  interface ChartHookOption {   type?: Ref<ChartType>;   el: ShallowRef<HTMLElement>; }  /**  *  視口變化時echart圖表自適應調整  */ class ChartsResize {   #charts = new Set<echarts.ECharts>(); // 緩存已經創(chuàng)建的圖表實例   #timeId = null;   constructor() {     window.addEventListener("resize", this.handleResize.bind(this)); // 視口變化時調整圖表   }   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();  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;   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); // 將圖表實例添加到緩存中     initEvent(); // 添加事件支持   };    /**    * 初始化事件,按需綁定事件    */   const attrs = useAttrs();   const initEvent = () => {     Object.keys(attrs).forEach(attrKey => {       if (/^on/.test(attrKey)) {         const cb = attrs[attrKey];         attrKey = attrKey.replace(/^on(Chart)?/, "");         attrKey = `${attrKey[0]}${attrKey.substring(1)}`;         typeof cb === "function" && charts.value?.on(attrKey, cb as () => void);       }     });   };    onBeforeUnmount(() => {     chartsResize.remove(charts.value); // 移除緩存   });    return {     charts,     setOptions,     initChart,     initEvent   }; };  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: GC  * @LastEditTime: 2022-06-02 17:45:48  */ // import * as echarts from 'echarts/core'; import * as echarts from 'echarts' import { XAXisComponentOption, YAXisComponentOption } from 'echarts';  import { ECElementEvent, SelectChangedPayload, HighlightPayload,  } from 'echarts/types/src/util/types'  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'  // echarts事件 namespace ChartsEvents {   // 鼠標事件類型   type MouseEventType = 'click' | 'dblclick' | 'mousedown' | 'mousemove' | 'mouseup' | 'mouseover' | 'mouseout' | 'globalout' | 'contextmenu' // 鼠標事件類型   type MouseEvents = {     [key in Exclude<MouseEventType,'globalout'|'contextmenu'> as `chart${Capitalize<key>}`] :ECElementEvent   }   // 其他的事件類型極參數(shù)   interface Events extends MouseEvents {     globalout:ECElementEvent,     contextmenu:ECElementEvent,     selectchanged: SelectChangedPayload;     highlight: HighlightPayload;     legendselected: { // 圖例選中后的事件       type: 'legendselected',       // 選中的圖例名稱       name: string       // 所有圖例的選中狀態(tài)表       selected: {         [name: string]: boolean       }     };     // ... 其他類型的事件在這里定義   }     // echarts所有的事件類型   type EventType = keyof Events }  export {   BaseOption,   ChartType,   LineECOption,   BarECOption,   Options,   PieECOption,   FunnelOption,   GaugeECOption,   EChartsOption,   ChartsEvents }
      登錄后復制

      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",     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;
      登錄后復制

      項目中使用

      index.vue

      <template>   <div>     <section>       <div class="device-statistics chart-box">         <div>累計設備接入統(tǒng)計</div>         <v-charts           type="bar"           :options="statisDeviceByUserObjectOpts"           @selectchanged="selectchanged"           @chart-click="handleChartClick"         />       </div>       <div class="coordinate-statistics chart-box">         <div>坐標數(shù)據(jù)接入統(tǒng)計</div>         <v-charts type="bar" :options="statisCoordAccess" />       </div>     </section>   </div> </template> <script setup> import {   useStatisDeviceByUserObject, } from "./hooks"; // 設備分類統(tǒng)計 const { options: statisDeviceByUserObjectOpts,selectchanged,handleChartClick } = useStatisDeviceByUserObject(); </script>
      登錄后復制

      /hooks/useStatisDeviceByUserObject.ts

      export const useStatisDeviceByUserObject = () => {   // 使用chartsOptions確保所有傳入v-charts組件的options數(shù)據(jù)都是## shallowReactive淺層作用形式,避免大量數(shù)據(jù)導致性能問題   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賦值時要注意options是淺層響應式       options.xAxis = { data: xData };        options.series = [{ ...options.series[0], data: sData }];     });   };      // 事件   const selectchanged = (params: ChartsEvents.Events["selectchanged"]) => {     console.log(params, "選中圖例了");   };    const handleChartClick = (params: ChartsEvents.Events["chartClick"]) => {     console.log(params, "點擊了圖表");   };      onMounted(() => {     init();   });   return {     options,     selectchanged,     handleChartClick   }; };
      登錄后復制

      使用時輸入@可以看到組件支持的所有事件:

      聊聊vue3中echarts用什么形式封裝最好?(代碼詳解)

      • 推薦學習:《vue.js視頻教程》

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號