最近项目中要用到很多eCharts图表组件,需要在窗口尺寸发生变化时,重置图表的大小,此时如果在每个组件里面都去实现一段监听代码,代码重复太多了,此时就可以使用混入来解决这个问题,mixins是Vue提供的一种混合机制,用来更高效的实现组件内容的复用。
JS代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import { debounce } from "lodash"; const resizeChartMethod = Symbol();
export default { data() { return { myChart: null, [resizeChartMethod]: null }; }, created() { var _this = this; this[resizeChartMethod] = debounce(function() { if (_this.myChart) { _this.myChart.resize(); } }, 100); window.addEventListener("resize", this[resizeChartMethod]); }, methods: {}, beforeDestroy() { window.removeEventListener("reisze", this[resizeChartMethod]); } };
|
图表组件代码
1 2 3
| <template> <div class="chart"></div> </template>
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| import echartMixins from './echarts-mixins' export default { mixins: [echartMixins], data() { return { chart: null } }, created() { this.chart = echarts.init(this.$el) } }
|