1.在vue中添加Echarts图表使用详解
使用npm添加package.json文件中的配置并下载相关npm包依赖
npm install echarts --save
然后在需要创建图表的组件中引入
// 引入echarts
import echarts from "echarts"
在模板中创建所需的dom
<div class="echarts-wrap">
<div class="item1-l" ref="myChart"></div>
<div class="item1-r" ref="myPie"></div>
</div>
写入js
<script>
export default {
name: "Index",
data() {
return {
myChart: null, //关键一
myPie: null,
}
},
mounted() {
this.drawLine();
this.drawPie();
this.init(); //让echarts窗口自适应 //关键二
},
methods: {
drawLine() {
// 基于准备好的dom,初始化echarts实例
this.myChart = echarts.init(this.$refs.myChart);
this.myChart.setOption({
title: {
text: "折线图"
},
tooltip: {
trigger: "axis"
},
legend: {
y: "bottom",
data: ["2的指数", "3的指数"]
},
grid: {
left: "3%",
right: "5%",
bottom: "10%",
containLabel: true
},
xAxis: {
type: "category",
boundaryGap: false,
data: ['一', '二', '三', '四', '五']
},
yAxis: {
type: "value"
},
series: [{
name: "2的指数",
type: "line",
data: ['10', '20', '30', '40', '50']
},
{
name: "3的指数",
type: "line",
data: ['20', '30', '40', '50', '60']
}
]
});
},
drawPie() {
this.myPie = echarts.init(this.$refs.myPie);
this.myPie.setOption({
title: {
text: '某站点用户访问来源',
subtext: '纯属虚构',
x: 'center'
},
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
left: 'left',
data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
},
series: [{
name: '访问来源',
type: 'pie',
radius: '55%',
center: ['50%', '60%'],
data: [{
value: 335,
name: '直接访问'
},
{
value: 310,
name: '邮件营销'
},
{
value: 234,
name: '联盟广告'
},
{
value: 135,
name: '视频广告'
},
{
value: 1548,
name: '搜索引擎'
}
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
});
},
init() { //关键三
setTimeout(() => {
window.addEventListener('resize', () => {
this.myChart.resize();
this.myPie.resize();
})
}, 20)
},
destroyed() { //关键四
window.removeEventListener('resize', this.init, 20)
}
}
}
</script>
参考博文:
项目中报错Cannot read property 'getAttribute' of undefined解决