组件封装调用
1.如果是单个组件只需要使用一次的话
var chartDom = document.getElementById('map');
2.如果需要多次复用这个组件的话,我们可以使用 $refs
this.myChart = echarts.init(this.$refs.chartDom);
子组件源码
<template> //地图容器 <div id="map" ref="chartDom"></div> </template> <script> const echarts = require("echarts/lib/echarts"); //引入地图json文件 export default { name: "map", props: ["chart", "inRange"], data() { return { chartData: [], myChart: null }; }, destroyed() { window.removeEventListener("resize", this.resizeFn, true); this.myChart.dispose(); }, watch: { chart: { handler: function(val) { this.$nextTick(() => { let clientHeight = Math.floor(document.getElementsByClassName("layout")[0].offsetHeight); this.barWidth = Math.floor(clientHeight * 0.013); this.chartData = val; this.initChart(); }); }, immediate: true } }, mounted() {}, methods: { initChart() { echarts.registerMap(json); //只需要调用一次 var chartDom = document.getElementById('map'); this.myChart = echarts.init(chartDom); //多次复用使用 this.myChart = echarts.init(this.$refs.chartDom); let data = []; let maxSnqncl = 0; this.chartData.forEach(item => { data.push({ name: item.xzqhmc, value: item.dncls }); if (item.dncls > maxSnqncl) { maxSnqncl = item.dncls; } }); var option; option = { grid: { left: "20%", containLabel: true }, visualMap: { min: 0, max: maxSnqncl, bottom: 0, left: 10, itemWidth: 10, itemHeight: 60, text: "项目数量", realtime: true, calculable: true, inRange: { // color: ['#193369', '#0488F8'] color: [this.inRange[0], this.inRange[1]] }, textStyle: { color: "#ccc" } }, series: [ { type: "map", map: "zibo", zoom: 1.26, label: { normal: { show: true, color: "#ffffff", fontSize: 8 }, emphasis: { show: false } }, data: data, roam: true, itemStyle: { normal: { areaColor: "#0d0059", borderColor: "#389dff", borderWidth: 0.5 }, emphasis: { areaColor: "#17008d", areaColor: this.inRange[1], shadowOffsetX: 0, shadowOffsetY: 0, shadowBlur: 5, borderWidth: 0, shadowColor: "rgba(0, 0, 0, 0.5)" } } } ] }; option && this.myChart.setOption(option); window.addEventListener("resize", this.resizeFn, true); }, resizeFn() { this.myChart.resize(); } } }; </script> <style lang="scss" scoped> #emap { width: 100%; height: 100%; } </style>
复制
父组件引入传参就可以实现