1、安装
npm install echarts --save
2、vue2中使用Echarts
在main.js文件中
// 引入echarts
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
给定一个容器
<div id="myChart" :style="{width: '300px', height: '300px'}"></div>
echarts
初始化应在钩子函数mounted()
中,这个钩子函数是在el 被新创建的 vm.$el
替换,并挂载到实例上去之后调用
// 引入基本模板
let echarts = require('echarts/lib/echarts')
// 引入柱状图组件
require('echarts/lib/chart/bar')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
export default {
name: 'hello',
data() {
return {
msg: 'Welcome to Your Vue.js App'
}
},
mounted() {
this.drawLine();
},
methods: {
drawLine() {
// 基于准备好的dom,初始化echarts实例
let myChart = echarts.init(document.getElementById('myChart'))
// 绘制图表
title: {
text: '折线图堆叠'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
}
}
3、vue3中使用Echarts
因为setup
中没有this
,而且这时候还没有渲染,所以在setup
中 ,可以使用provide/inject
来把echart
引入进来
在根组件里引入echart,一般是App.vue
import * as echarts from 'echarts'
import { provide } from 'vue'
export default {
name: 'App',
setup(){
provide('echarts',echarts) //provide
},
components: {
}
}
这里需要注意的是import * as echarts from 'echarts'
, 不能 import echarts from 'echarts'
,这样会报错,因为5,0版本的echarts的接口已经变成了下面这样:
export {
EChartsFullOption as EChartsOption,
connect,
disConnect,
dispose,
getInstanceByDom,
getInstanceById,
getMap,
init,
registerLocale,
registerMap,
registerTheme
};
在需要使用的页面,定义div
<div id="home-page-traffic_chart" style="width: 600px; height: 280px">
然后在需要使用到Echarts的页面inject
export default {
name: 'data_page',
setup () {
const trafficData = ref({})
const echarts = inject('echarts')
onMounted(() => {
const myChart = echarts.init(document.getElementById('home-page-traffic_chart'))
// 绘制图表
myChart.setOption({
title: {
text: '今日话务统计'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: '直接访问',
type: 'bar',
barWidth: '60%',
data: [10, 52, 200, 334, 390, 330, 220]
}
]
})
window.onresize = function () {
myChart.resize()
}
})
return {
}
}
}
效果图: