在vue2.x中使用echarts
1、通过npm获取echarts
npm install echarts --save
2、在vue项目中引入echarts
在 main.js 中添加下面两行代码
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
注: 最新版本的echarts全局配置Vue.prototype.$echarts = echarts无效,可在调用echarts统计图的文件里用单独导入 import * as echarts from "echarts";
经测试 "echarts": "^4.9.0" 支持全局引入。
3、新建Echarts.vue文件
在 template 中添加一个存放echarts的‘div’容器
添加 myEcharts() 方法,将官方文档中的script内容复制到myEcharts()中
修改 echarts.init() 为 this.$echarts.init() ,因为上面第二部,将echarts保存到全局变量$echarts中。
在mounted中调用myEcharts()方法
<!-- 在Echarts.vue文件中 -->
<template>
<div class="Echarts">
<div id="main" style="width: 600px;height: 400px;"></div>
</div>
</template>
<script>
export default {
name: 'Echarts',
methods: {
myEcharts(){
var myChart = this.$echarts.init(document.getElementById('main'));
//配置图表
var option = {
title: {
text: 'echarts入门示例',
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫','羊毛衫','雪纺衫','裤子','高跟鞋','袜子']
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5,20,36,10,10,20]
}]
};
myChart.setOption(option);
}
},
mounted(){
this.myEcharts();
}
}
</script>
<style>
</style>
注:本例函数中使用ES6写法。mounted(){}等同于mounted:function(){}。myEcharts()方法同理。最后添加进行路由配置。
vue3 配置echarts(组合式API)
安装
npm install echarts vue-echarts
使用
<script setup>
import * as echarts from "echarts";
import { onMounted } from "vue";
//声明周期函数,自动执行初始化
onMounted(() => {
init();
});
//初始化函数
function init() {
// 基于准备好的dom,初始化echarts实例
let Chart = echarts.init(document.getElementById("main"));
// 绘制图表
let options = {
title: {
text: "ECharts 入门示例",
},
tooltip: {},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
},
yAxis: {},
series: [
{
name: "销量",
type: "bar",
data: [5, 20, 36, 10, 10, 20],
},
],
};
// 渲染图表
Chart.setOption(options);
}
</script>
<template>
<div id="main" style="height: 200px;width:200px"></div>
</template>