当前位置: 代码迷 >> 综合 >> Vue中使用echarts,帮你解决遇到的各种坑~~
  详细解决方案

Vue中使用echarts,帮你解决遇到的各种坑~~

热度:36   发布时间:2023-09-22 21:14:51.0

笔者在之前的工作中没有遇到vue中使用echarts的情况,以下是我的爬坑之路,还望笑纳。

1、使用npm或yarn(推荐yarn,npm装的可能启动项目后报错 xxxx 'new' 具体错误信息忘记了, 这时你要先找到node_modules中的echarts文件夹,整个删掉,或者使用命令行删除。然后使用yarn重装,如果还启动不了,那就用cnpm装)安装echarts:

npm install echarts --save    // npm
yarn add echarts    //yarn

官方文档点击这里,里面不仅有引入教程,还有按需引入教程,如果你在纠结是安装vue-echarts还是vue-chartjs,或者不知道这俩是不是vue版的官方版,笔者作为过来人告诉你,这俩都不要用,就用echarts!!!这俩之前如果安装过记得卸载,命令如下:

npm uninstall echarts // npm
yarn remove echarts // yarn

2、上面的官方文档链接已经能解决静态图表使用了。如果遇到页面刷新后接口数据加载不出图表的情况,记住,不要信网上的使用watch监听的教程,一点用没有!!!请按照下面的代码来处理:

<template><div class="container"><div class="echarts" id="pie"></div></div>
</template><script>
// 引入eCharts
import ECharts from 'echarts'
// 接口方法,用不到请干掉
import { getHomePagePie } from '@/api/statistics'export default {name: 'MyHome',data () {},methods: {// 加载方法drawChartPie () {// 接口方法,用不到请干掉getHomePagePie().then(res => {const option = {// grid: {//   x: 80,//   x2: 22,//   y2: 22// },// title: {//   text: '某站点用户访问来源',//   subtext: '纯属虚构',//   x: 'center'// },tooltip: {trigger: 'item',formatter: '{b} : {c} ({d}%)'},series: [{name: '地区',type: 'pie',avoidLabelOverlap: true, // 是否启用防止标签重叠策略selectedMode: 'single',radius: ['25%', '63%'],center: ['50%', '46%'],label: {normal: {fontWeight: 'bold',color: '#333',formatter: '{b} : {d}%'}},data: res.data,          // 这里是异步数据,数据结构请看官网官方实例中的饼图itemStyle: {emphasis: {shadowBlur: 10,shadowOffsetX: 0,shadowColor: 'rgba(0, 0, 0, 0.5)'}}}]}const myChartPie = ECharts.init(document.getElementById('pie'))myChartPie.setOption(option)}).catch(_=>{// 错误信息  })}},// mounted 你懂的不能换的亲mounted () {// 注意这里$nextTick方法不能少this.$nextTick(() => {this.drawChartPie()})}
}
</script>
<style lang="less" scoped>
.container {.echarts {height: 100%;}
}
</style>

笔者亲测可行,如果你遇到了无底洞,把代码贴出来把,或者去问答提问,总会有解决的办法。