vue 中使用 echarts
- 1、下载 指定版本 的依赖包
npm install echarts@^4 vue-echarts@^4
- 2、main.js 中引用
import echarts from 'echarts';
Vue.prototype.$echarts = echarts;
- 3、运用: 例如在 home.vue 使用
<div id="myChart" style="width: 100%; height: 500px"></div>
<script>
export default {
mounted () {
this.$nextTick(() => {
this.drawLine(['1-2', '1-8', '1-9', '1-88', '2-5', '2-9', '4-3', '5-6', '5-9', '5-61', '7-8', '7-11', '7-31', '8-11']);
});
// 适应浏览器窗口变化
window.addEventListener('resize', this.chartResize);
},
destroyed () {
// 离开当前页面销毁监听
window.removeEventListener('resize', this.chartResize);
},
methods: {
drawLine (xAxisData) {
let endNum = 30;
// X 轴计算出固定显示多少个数值
if (xAxisData.length > 30) {
endNum = 100 / (xAxisData.length / 30);
}
let option = {
title: {
text: '小程序访问趋势图',
subtext: '纯属虚构'
},
tooltip: {
trigger: 'axis'
},
toolbox: {
show: true,
feature: {
dataView: { readOnly: false },
magicType: { type: ['line', 'bar'] },
restore: {},
saveAsImage: {}
}
},
legend: {
data: ['访问人数', '访问次数', '平均停留时长'],
},
color: ['#37A2FF', '#FF0087', '#FFBF00'], // 示例颜色
grid: {
left: '2%',
right: '4%',
bottom: '3%',
containLabel: true
},
dataZoom: [
{
show: true,
start: 0, // 开始的百分比
end: endNum // 结束的百分比
},
{
startValue: '1-2'
}, {
type: 'inside'
}],
xAxis: {
type: 'category',
// data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
data: xAxisData
},
yAxis: {
type: 'value'
},
series: [
{
name: '访问人数',
data: [120, 200, 150, 80, 70, 110, 130, 20, 20, 50, 1, 7, 110],
type: 'line',
smooth: true, // 平滑折线图
markPoint: {
data: [
{ type: 'max', name: '最大值' },
{ type: 'min', name: '最小值' }
]
},
},
{
name: '访问次数',
data: [130, 150, 160, 770, 40, 190, 230, 50, 60, 40, 18, 47, 310],
type: 'line',
smooth: true, // 平滑折线图
markPoint: {
data: [
{ type: 'max', name: '最大值' },
{ type: 'min', name: '最小值' }
]
},
},
{
name: '平均停留时长',
data: [160, 1000, 880, 80, 90, 150, 110, 210, 220, 150, 111, 71, 210],
type: 'line',
smooth: true, // 平滑折线图
markPoint: {
data: [
{ type: 'max', name: '最大值' },
{ type: 'min', name: '最小值' }
]
},
},
]
};
// 基于准备好的dom,初始化echarts实例, null, {renderer: 'svg'} 是为了让字体不会模糊
this.myChart = this.$echarts.init(document.getElementById('myChart'), null, {renderer: 'svg'})
// 绘制图表
this.myChart.setOption(option, true);
},
// 让图表随着浏览器窗口变化自适应
chartResize () {
this.myChart.resize();
}
}
</script>
网友评论