Vue项目中关于Echarts的使用

330 阅读1分钟

1. 安装

npm install echarts

2. 全局引入

// 在 main.js 入口文件中

// 注意:v5版本去除 default exports 的支持,所以一定要按版本进行选用,否则会报错
import * as echarts from 'echarts'      // echarts v5 版本使用
import echarts from 'echarts'           // echarts v4 版本使用

// 挂载到Vue原型上
Vue.prototype.$echarts = echarts

3. 在Vue组件中使用

// 在Vue组件中
<template>
    // 容器
  <div style="width: auto; height: 400px" id="main"> </div>
</template>

<script>
//通过this.$echarts来使用
  export default {
    name: "page",
    mounted(){
    	// 在通过mounted调用即可
		this.echartsInit()
	},
    methods: {
	    //初始化echarts
	    echartsInit() {
	    	//柱形图
	    	//因为初始化echarts 的时候,需要指定的容器 id='main'
			this.$echarts.init(document.getElementById('main')).setOption({
			    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)'
			        }
			    }]
			})
		}
	    	
    }
  }
</script>