关于Vue mixins 混用在echart当中的应用
Liuyi 2021-07-07 Vue
在项目实践中echart图表不会随着视图的更改去自适应,需要自己手动去配置重新渲染。因为不同的图表只是数据跟配置项不同自然而然的,我们可以想到将图表抽出来分成一个个组件,每个图表组件负责对传进来的数据进行处理以及渲染。而根据数据重新渲染的操作我们可以使用 mixins 去抽出统一的逻辑。
混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。mixins。
// echartComponment
<template>
<div ref="echartsLineTendency" style="width: 100%; height: 100%"></div>
</template>
<script>
import resize from '@/mixins/resize';
export default {
props: {
echartData: {
type: Array,
default: () => [],
},
},
mixins: [resize],
data() {
return {
chart: null,
};
},
created() {
},
methods: {
handleEchartOption() {
const option = {
};
return option;
},
drawModel() {
this.chart = this.$echarts.init(this.$refs.echartsLineTendency);
this.chart.setOption(this.handleEchartOption());
},
},
watch: {
echartData: {
handler() {
this.drawModel();
},
deep: true,
},
},
mounted() {
this.drawModel();
},
};
</script>
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { debounce } from '@/utils';
// TODO 学习混入(mixins)
export default {
data() {
return {
$_sidebarElm: null,
$_resizeHandler: null,
};
},
mounted() {
this.initListener();
},
activated() {
if (!this.$_resizeHandler) {
// avoid duplication init
this.initListener();
}
// when keep-alive chart activated, auto resize
this.resize();
},
beforeDestroy() {
this.destroyListener();
},
deactivated() {
this.destroyListener();
},
methods: {
// use $_ for mixins properties
// https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential
$_sidebarResizeHandler(e) {
if (e.propertyName === 'width') {
this.$_resizeHandler();
}
},
initListener() {
this.$_resizeHandler = debounce(() => {
this.resize();
}, 100);
window.addEventListener('resize', this.$_resizeHandler);
// this.$_sidebarElm = document.getElementsByClassName(
// 'sidebar-container'
// )[0];
// this.$_sidebarElm &&
// this.$_sidebarElm.addEventListener(
// 'transitionend',
// this.$_sidebarResizeHandler
// );
},
destroyListener() {
window.removeEventListener('resize', this.$_resizeHandler);
this.$_resizeHandler = null;
// this.$_sidebarElm &&
// this.$_sidebarElm.removeEventListener(
// 'transitionend',
// this.$_sidebarResizeHandler
// );
},
resize() {
const { chart } = this;
if (chart) {
chart.resize();
}
},
},
};
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73