步骤一:引入echarts.js文件
步骤二:准备一个echarts实例图表的盒子(div必须存在width,height)
步骤三:初始化echarts实例对象(参数,dom,决定图标最终呈现的位置)
步骤四:准备配置项
步骤五:将配置项设置给echarts实例对象
<template>
<div class="com-container">
<!-- 图表容器-->
<div class="com-chart" ref="seller_ref"></div>
</div>
</template>
<script>
export default {
data(){
return{
chartInstance:null,//图表对象
allData: null,//服务器返回的数据
}
},
mounted() {
this.initChart()
this.getData()
//监听器
window.addEventListener('resize', this.screenAdapter)
//在页面加载完成时,主动进行屏幕的适配
this.screenAdapter()
},
destroyed() {
//组件销毁时,需要将监听器取消掉
window.removeEventListener('resize', this.screenAdapter)
},
methods:{
// 1. 初始化echartInstance对象
initChart(){
this.chartInstance=this.$echarts.init(this.$refs.seller_ref)
const initOption={}
this.chartInstance.setOption(initOption)
},
// 2. 获取服务器的数据
async getData(){
const {data:ret}= await this.$http.get('seller')
this.allData=ret
//更新
this.updateChart()
},
// 3.更新图表
updateChart(){
const sellerNames=this.allData.map((item)=>{
return item.name
})
const sellerValues=this.allData.map((item)=>{
return item.value
})
const option={
xAxis:{
type:'value'
},
yAxis:{
type: 'category',
data:sellerNames
},
series:[
{
type:'bar',
data:sellerValues
}
]
}
this.chartInstance.setOption(option)
},
// 当浏览器的大小发生变化时,会调用的方法,来完成屏幕的适配
screenAdapter() {
// console.log(this.$refs.seller_ref.offsetWidth)
//const titleFontSize = this.$refs.seller_ref.offsetWidth / 100 * 3.6
//和分辨率大小相关的配置项
const adapterOption = {}
this.chartInstance.setOption(adapterOption)
// 手动调用图表对象的resize才能产生效果
this.chartInstance.resize()
},
}
}
</script>
<style scoped>
</style>