search
HomeWeb Front-endVue.jsHow Vue encapsulates Echarts charts

How Vue encapsulates Echarts charts

Aug 12, 2021 pm 05:53 PM
echartsvue.jschart

Before we start, we first follow the normal component registration process, create a new component named radar-chart in the project components directory, and then introduce the component to a Demo page for use.

New radar-chart component content:

// radar-chart.vue (子组件)
<template>
    <p style="width: 100%; height: 100%;"></p>
</template>

<script>
export default {
    name: &#39;radar-chart&#39;
};
</script>

<style scoped>

</style>

Demo page code:

// demo.vue (父组件)
<template>
    <p style="border: 1px solid black; width: 400px; height: 300px; margin: 5px;">
        <radar-chart></radar-chart>
    </p>
</template>

<script>
import radarChart from &#39;@/components/proj-components/echarts/radar-chart&#39;;
export default {
    name: &#39;radar-chart-demo&#39;,
    components: {
        radarChart,
    },
};
</script>

<style scoped>

</style>

Demo page rendering 1:

How Vue encapsulates Echarts charts

Initialize the chart

After the preparation work is completed, what we have to do is to introduce ECharts and initialize an ECharts instance in the component. Here you can first copy the instance from the official website and data.
(1) Introduce ECharts in radar-chart.vue:

// radar-chart.vue (子组件)
import echarts from &#39;echarts&#39;;

(2) Create chart configuration data in methods. For data format, please refer to Echarts official website:

// radar-chart.vue (子组件)

    methods: {
        // 初始化图表配置
        initOption() {
            let vm = this;
            vm.option = {
                title: {
                    text: &#39;基础雷达图&#39;
                },
                tooltip: {},
                legend: {
                    data: [&#39;预算分配(Allocated Budget)&#39;, &#39;实际开销(Actual Spending)&#39;]
                },
                radar: {
                    // shape: &#39;circle&#39;,
                    name: {
                        textStyle: {
                            color: &#39;#fff&#39;,
                            backgroundColor: &#39;#999&#39;,
                            borderRadius: 3,
                            padding: [3, 5]
                        }
                    },
                    indicator: [{ name: &#39;销售(sales)&#39;, max: 6500}, { name: &#39;管理(Administration)&#39;, max: 16000}, { name: &#39;信息技术(Information Techology)&#39;, max: 30000}, { name: &#39;客服(Customer Support)&#39;, max: 38000}, { name: &#39;研发(Development)&#39;, max: 52000}, { name: &#39;市场(Marketing)&#39;, max: 25000}]
                },
                series: [{
                    name: &#39;预算 vs 开销(Budget vs spending)&#39;,
                    type: &#39;radar&#39;,
                    // areaStyle: {normal: {}},
                    data: [{value: [4300, 10000, 28000, 35000, 50000, 19000], name: &#39;预算分配(Allocated Budget)&#39;}, {value: [5000, 14000, 28000, 31000, 42000, 21000], name: &#39;实际开销(Actual Spending)&#39;}]
                }]
            };
        },
    },

(3 ) Initialize the chart: In the component hook mounted method:

// radar-chart.vue (子组件)
    mounted() {
        this.initOption();
        this.$nextTick(() => { // 这里的 $nextTick() 方法是为了在下次 DOM 更新循环结束之后执行延迟回调。也就是延迟渲染图表避免一些渲染问题
            this.ready();
        });
    },

In methods:

// radar-chart.vue (子组件)
   ready() {
      let vm = this;
      let dom = document.getElementById(&#39;radar-chart&#39;);

      vm.myChart = echarts.init(dom);
      vm.myChart && vm.myChart.setOption(vm.option);
   },

Demo page rendering 2:

How Vue encapsulates Echarts charts

There are three steps here, including introducing ECharts, initializing the chart configuration, and initializing the chart. Finally, you can see on the Demo page that the radar chart of ECharts has been initially displayed in the project.

Extract chart configuration properties (emphasis)

We have successfully created a radar chart above, but it is obvious that the data in radar-chart.vue is written Dead and cannot be called repeatedly. Next, let’s start with packaging.

The idea of ​​encapsulation is as follows:

1. demo.vue passes a set of personalized data to radar-chart.vue

2. radar-chart.vue passes props option receives data

3. Refine the received data and overwrite the configuration data option

4. Initialize the chart

Specific implementation: Pass data to the sub-component in data Define variables and assign values ​​in mounted

// demo.vue (父组件)
<template>
    <p style="border: 1px solid black; width: 900px; height: 600px; margin: 5px;">
        <radar-chart :indicator="indicator" :legendData="radarData"></radar-chart>
    </p>
</template>

<script>
import radarChart from &#39;@/components/proj-components/echarts/radar-chart&#39;;
export default {
    name: &#39;radar-chart-demo&#39;,
    components: {
        radarChart,
    },
    mounted() {
        this.indicator = [
            { name: &#39;销售&#39;, max: 6500 },
            { name: &#39;管理&#39;, max: 16000 },
            { name: &#39;信息技术&#39;, max: 30000 },
            { name: &#39;客服&#39;, max: 38000 },
        ];
        this.radarData = [
            {
                value: [4000, 15000, 26000, 21000],
                name: &#39;实际开销(Actual Spending)&#39;,
            }
        ];
    },
    data() {
        return {
            indicator: [], // 雷达指示器数据
            legendData: [], // 雷达图例数据
        };
    },
};
</script>

<style scoped>

</style>

Receive data from the parent component in props

// radar-chart.vue (子组件)

    props: {
        // 指示器数据,必传项
        // 格式举例 [{ name: &#39;a&#39;, max: 1},{ name: &#39;a&#39;, max: 1},{ name: &#39;a&#39;, max: 1}]
        indicator: {
            type: Array,
            default: () => []
        },
        // 图例数据,必填项。
        // 格式举例 [{ value: [5000, 14000, 28000], name: &#39;name&#39; },{ value: [5000, 14000, 28000], name: &#39;name&#39; }]
        legendData: {
            type: Array,
            default: () => []
        },
    },

Update chart data option in ready() If you update the indicator and data attributes here value, there is no need to initialize these two values ​​​​in initOption()

// radar-chart.vue (子组件)

    ready() {
       let vm = this;
       let dom = document.getElementById(&#39;radar-chart&#39;);

       vm.myChart = echarts.init(dom);

       // 得到指示器数据
       vm.option.radar.indicator = vm.indicator;
       // 得到图例数据
       vm.option.series[0].data = vm.legendData;

       vm.myChart && vm.myChart.setOption(vm.option);
    },

Demo page rendering picture 3:

How Vue encapsulates Echarts charts

##Detail optimization and other considerations:

1. When a page has multiple charts, chart IDs are automatically generated.

// radar-chart.vue (子组件)
<template>
    <p :id="chartId" style="height: 100%; width: 100%;"></p>
</template>

<script>
let chartIdSeed = 1;

export default {
    data() {
        return {
            chartId: 1,
        };
    },
    mounted() {
        let vm = this;
        vm.chartId = &#39;radar-chart_&#39; + chartIdSeed++;
    },
    methods: {
        let vm = this;
        let dom = document.getElementById(vm.chartId);
    }
};
</script>

2. Chart data attributes are received with props, and the default configuration attributes of the chart are saved with defaultConfig. The configuration attribute chartConfig passed in by the parent component is directly obtained through $attrs, and finally merged into finallyConfig for use, which is conducive to expansion and maintenance.

// radar-chart.vue (子组件)

<script>
export default {
    data() {
        return {
            // 默认配置项。以下配置项可以在父组件 :chartConfig 进行配置,会覆盖这里的默认配置
            defaultConfig: {
                tooltipShow: true
            },
            finallyConfig: {}, // 最后配置项
        };
    },
    mounted() {
        // 在这里合并默认配置与父组件传进来的配置
        vm.finallyConfig = Object.assign({}, vm.defaultConfig, vm.$attrs.chartConfig);
    },
    methods: {
        initOption() {
            vm.option = {
                tooltip: {
                    show: vm.finallyConfig.tooltipShow, // 在这里使用最终配置
                },
            }
        },
    }
};
</script>

3. Use watch to monitor chart data updates

// radar-chart.vue (子组件)
    watch: {
        legendData() {
            this.$nextTick(() => {
                this.ready();
            });
        }
    },

4. Add window resize event and chart click event

// radar-chart.vue (子组件)

export default {
    data() {
        return {
            chartResizeTimer: null, // 定时器,用于resize事件函数节流
        };
    },
    methods: {
        ready() {
            // 添加窗口resize事件
            window.addEventListener(&#39;resize&#39;, vm.handleChartResize);
            
            // 触发父组件的 @chartClick 事件
            vm.myChart.on(&#39;click&#39;, function(param) {
                vm.$emit(&#39;chartClick&#39;, param);
            });
        },
        
        // 处理窗口resize事件
        handleChartResize() {
            let vm = this;
            clearTimeout(vm.chartResizeTimer);
            vm.chartResizeTimer = setTimeout(function() {
                vm.myChart && vm.myChart.resize();
            }, 200);
        },
    },
    beforeDestroy() {
        // 释放该图例资源,较少页面卡顿情况
        if (this.myChart) this.myChart.clear();
        // 移除窗口resize事件
        window.removeEventListener(&#39;resize&#39;, this.handleChartResize);
    }
};

[Related recommendations:《

vue.js Tutorial》】

The above is the detailed content of How Vue encapsulates Echarts charts. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.