vue项目中引用Echarts图表及遇到的问题
一、初始化使用npm安装echarts:
npm install echarts -S
//或
cnpm install echarts -S
二、在main.js中引入echarts:
import Vue from 'vue'
import echarts from 'echarts'
Vue.prototype.$echarts = echarts;
三、单页面引用案例:
<template>
<div class="exercisesList">
<div
style="width: auto;height: 400px;margin-top: 20px;"
ref="echart"
class="echart"
>
</div>
</div>
</template>
<script>
export default {
name: "echart",
data() {
return {};
},
mounted() {
this.$nextTick(() => {
this.getEcharts();
});
},
methods: {
getEcharts() {
let myChart = this.$echarts.init(this.$refs.echart);
myChart.setOption({
title: { text: "难易度分析" },
tooltip: {
trigger: "item",
},
legend: {
top: "5%",
left: "center",
},
series: [
{
type: "pie",
radius: "50%",
data: [
{ value: 104, name: "容易" },
{ value: 73, name: "较易" },
{ value: 58, name: "一般" },
{ value: 48, name: "较难" },
{ value: 30, name: "困难" },
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
},
],
});
},
},
};
</script>
<style lang="scss" scoped>
</style>
效果图如下:
四、使用中遇到的问题:
尝试了好几种办法都未果,最后使用this.$nextTick(() => {});成功解决,产生问题原因是,在标签还没有加载的时候该方法就被调用了,解决办法:
mounted() {
this.$nextTick(() => {
this.getEcharts();
});
},
其他办法(自行选择):
1.如果不需要操作dom就在created,操作dom就在mounted里面。
2.使用v-show来控制是否显示图形,v-show是控制图形是否显示,只是dom是否隐藏了的问题,dom树也是创建完成了的
3.this.$nextTick(() => {this.getEcharts()});
4.定时器setTimeout(() => { this.getEcharts() }, 0)