最近Vue撸一个数据监控平台,在封装echarts可复用组件:

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
<template>
<div :id="uniqueID"></div>
</template>
<script>
import uuid from 'uuid/v1'
export default {
name: 'chart',
props: {
options: {
type: Array
}
},
data () {
return {
uniqueID: ''
}
},
created () {
this.uniqueID = uuid()
},
mounted () {
const options = {
title: {
x: 'center'
},
...
},
- let chart = echarts.init(querySelector(this.uniqueID))
+ let chart = echarts.init(getElementById(this.uniqueID))
chart.setOption(options)
}
}
</script>

这样ID不会重复,一个页面调用复用组件完全没问题。但这里有一个问题:uuid()生成的ID有可能是以数字开头的,这时候querySelector会报错:‘3fdf234-3fds2432-3fsd2432’ is not a valid selector .这时候有两个选择:1.给uuid()生成的ID前面增加一个固定字符串,继续使用querySelector。2.使用getElementById()原生API.

选择方案2的理由很简单:getElementById()效率更好,而且无需拼接字符串;代码可以保持很好的简洁性与优雅性.