安装echarts
npm install echarts
封装 eCharts.vue
<template>
<div :id="id" :class="className"></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
name: "eCharts",
props: {
id: {
type: String,
require: true
},
className: {
type: String,
default: ''
},
options: {
type: Object,
default: () => ({})
},
/* upDate用于判断是否需要更新全部图形,
true 为更新全部图形(重新加载图形),
false 为追加数据,只更新部分数据图形
*/
upDate: {
type: Boolean,
default: true
}
},
data() {
return {
myChart: null,
}
},
mounted() {
this.initCharts()
},
watch: {
options: {
deep: true,
handler() {
if (this.upDate) {
this.initCharts()
}
}
},
},
methods: {
initCharts() {
let _this = this
this.myChart = echarts.init(document.getElementById(this.id))
this.myChart.clear() //清除echarts,防止图形变化重复渲染
this.myChart.setOption(this.options)
this.myChart.off() //防止多次点击图形
window.onresize = this.myChart.resize //自适应浏览器窗口大小
this.myChart.on('click', function (params) {
_this.$parent.clickEcharts(params,_this.id)
})//点击事件
this.myChart.on('datazoom', function (params) {
_this.$parent.dataZoomEcharts(params_this.id)
})//缩放或滑道事件
},
},
}
</script>
注册全局组件在 main.js 添加
import eCharts from "./components/eCharts";
Vue.component('eCharts',eCharts)
局部组件在当前需要使用的页面添加
import eCharts from "../../components/eCharts";
export default {
...
components: {
eCharts
},
...
}
实例
echartsDemo.vue
<template>
<div>
<e-charts id="echartsDemo"
class-name="echarts"
:options="options">
</e-charts>
</div>
</template>
<script>
export default {
name: "echartsDemo",
data() {
return {
options: {},
}
},
created() {
this.options = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(220, 220, 220, 0.8)'
}
}]
};
},
methods: {
clickEcharts(params,id) {
//id 可以区分一个页面多次使用组件时的点击事件,id就是调用组件传入的id
if (id === 'echartsDemo'){
alert('图形点击事件:' + params.name)
}
}
},
}
</script>
<style>
.echarts {
width: 100%;
height: 450px;
background-color: white;
}
</style>
如有问题请私信哦,有更优方法或者可以改进的地方欢迎评论留言~