Home >Web Front-end >Vue.js >How Vue encapsulates Echarts charts
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: 'radar-chart' }; </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 '@/components/proj-components/echarts/radar-chart'; export default { name: 'radar-chart-demo', components: { radarChart, }, }; </script> <style scoped> </style>
Demo page rendering 1:
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 'echarts';
(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: '基础雷达图' }, tooltip: {}, legend: { data: ['预算分配(Allocated Budget)', '实际开销(Actual Spending)'] }, radar: { // shape: 'circle', name: { textStyle: { color: '#fff', backgroundColor: '#999', borderRadius: 3, padding: [3, 5] } }, indicator: [{ name: '销售(sales)', max: 6500}, { name: '管理(Administration)', max: 16000}, { name: '信息技术(Information Techology)', max: 30000}, { name: '客服(Customer Support)', max: 38000}, { name: '研发(Development)', max: 52000}, { name: '市场(Marketing)', max: 25000}] }, series: [{ name: '预算 vs 开销(Budget vs spending)', type: 'radar', // areaStyle: {normal: {}}, data: [{value: [4300, 10000, 28000, 35000, 50000, 19000], name: '预算分配(Allocated Budget)'}, {value: [5000, 14000, 28000, 31000, 42000, 21000], name: '实际开销(Actual Spending)'}] }] }; }, },
(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('radar-chart'); vm.myChart = echarts.init(dom); vm.myChart && vm.myChart.setOption(vm.option); },
Demo page rendering 2:
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 '@/components/proj-components/echarts/radar-chart'; export default { name: 'radar-chart-demo', components: { radarChart, }, mounted() { this.indicator = [ { name: '销售', max: 6500 }, { name: '管理', max: 16000 }, { name: '信息技术', max: 30000 }, { name: '客服', max: 38000 }, ]; this.radarData = [ { value: [4000, 15000, 26000, 21000], name: '实际开销(Actual Spending)', } ]; }, data() { return { indicator: [], // 雷达指示器数据 legendData: [], // 雷达图例数据 }; }, }; </script> <style scoped> </style>
Receive data from the parent component in props
// radar-chart.vue (子组件) props: { // 指示器数据,必传项 // 格式举例 [{ name: 'a', max: 1},{ name: 'a', max: 1},{ name: 'a', max: 1}] indicator: { type: Array, default: () => [] }, // 图例数据,必填项。 // 格式举例 [{ value: [5000, 14000, 28000], name: 'name' },{ value: [5000, 14000, 28000], name: 'name' }] 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('radar-chart'); 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:
##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 = 'radar-chart_' + 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('resize', vm.handleChartResize); // 触发父组件的 @chartClick 事件 vm.myChart.on('click', function(param) { vm.$emit('chartClick', 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('resize', 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!