在公司做數據可視化需求的時候用到了echarts框架,下面是自己使用Vue結合echarts的封裝成一個可復用的組件的一些方法。
首先在自己的項目中安裝echarts、安裝命令為:
npm install echarts --save
之后在Vue項目中使用,比如現在這個組件的名字叫:EchartsComponent.vue,代碼如下
<template>
<div>
<div style="width:50%;height:200px;" :id="echarts" class="echarts" ref="echarts"></div>
</div>
</template>
<script>
// 引入echarts
import echarts from 'echarts'
export default {
name: 'EchartsComponents',
props: {
// 接收父組件傳遞過來的信息
chartData: {
type: Array,
default: ()=>[]
}
},
data () {
return {}
},
methods: {
drawChart () {
const vm = this
// 基於准備好的dom,初始化echarts實例
var myChart =echarts.init(document.getElementById(this.echarts))
// 繪制圖表
myChart.setOption({
title: {
text: 'ECharts 入門示例'
},
tooltip: {},
xAxis: {
data: this.chartData
},
yAxis: {},
series: [
{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
})
}
},
computed: {
echarts() {
return 'echarts' + Math.random()*100000
}
},
mounted: function () {
const vm = this
vm.$nextTick(()=> {
vm.drawChart()
})
},
created: () => {}
}
</script>
<style scoped>
</style>
這個組件在寫的時候需要有幾個注意的地方:
- 使用echarts.init這個方法來創建一個 ECharts 實例,返回 echartinstance,不能在單個容器上初始化多個 ECharts 實例,因此需要用到Vue的computed屬性來解決這個問題
- 因為把它封裝成了一個Vue組件,因此要注意父子組件之間的通信、需要用到props這個屬性
- 在Vue的生命周期mounted執行,並且在this.$nextTick里面執行這個方法,保證承若所有的子組件被掛載、能保證通過獲取到組件
然后在父組件中調用、這里比如父組件為Test.vue,代碼如下所示
<template>
<div>
<Row>
<i-col span="12"><EchartsCoponent :chartData="chartData1"/></i-col>
<i-col span="12"><EchartsCoponent :chartData="chartData2"/></i-col>
</Row>
</div>
</template>
<script>
import EchartsCoponent from './EchartsComponent'
export default {
name: 'Test',
data () {
return {
chartData1: ['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子'],
chartData2: ['蘋果', '香蕉', '橘子', '梨子', '櫻桃', '哈密瓜']
}
},
components: {
EchartsCoponent
},
mounted: function() {
const vm = this
vm.$nextTick(()=> {})
}
}
</script>
<style scoped>
</style>
里面使用到一些iview的樣式
這里需要注意的是需要把EchartsCoponent這個組件在Vue的components屬性里面注冊一下:
在頁面中的效果如下:

還有第二種方法寫組件,EchartsComponent.vue,代碼如下:
<template>
<div>
<div style="width:50%;height:200px;" ref="echarts"></div>
</div>
</template>
<script>
import echarts from 'echarts'
export default {
name: 'EchartsComponents',
props: {
chartData: {
type: Array,
default: ()=>[]
}
},
data () {
return {
count:1
}
},
methods: {
drawChart () {
const vm = this
// 基於准備好的dom,初始化echarts實例
var myChart = echarts.init(this.$refs.echarts)
// 繪制圖表
myChart.setOption({
title: {
text: 'ECharts 入門示例'
},
tooltip: {},
xAxis: {
data: this.chartData
},
yAxis: {},
series: [
{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
})
}
},
computed: {},
mounted: function () {
const vm = this
vm.$nextTick(()=> {
vm.drawChart()
})
},
created: () => {}
}
</script>
<style scoped>
</style>
主要使用到vue的ref屬性,不需要使用到計算屬性:
test.vue中代碼一樣、最中實現的效果是一樣的;
