一、安装echarts依赖
npm install echarts --save
二、在main.js中全局引入echarts
import * as echarts from 'echarts'
Vue.prototype.$echarts = echarts
三、在页面中引入echarts
① 用div装echarts图表,把他放到你想放的位置。
<div id="echart" style="width: 100%;height:300px"></div>
通过id来标识这个组件,这里的样式宽度和高度最好给一个,不然可能会加载不出来。
② 在methods中定义方法drawCharts,画出这个图表。
methods: {
drawChart() {
// 这里的echart同div里的id名相同即可
const myChart = this.$echarts.init(document.getElementById("echart"));
// option为一个设置图表格式的数组
myChart.setoption(this.option);
},
},
③ 记得这个方法的渲染不能放在create()里面,得放在mounted()里面
mounted() {
this.drawChart();
},
其中option就是对于这个图表的设置,官网中给出的例子option就是这个东西
④ 给一个简单的option
只需要照着官网的示例选取自己需要的option即可。
option: {
title: {
text: "测试用例",
left: "center",
},
tooltip: {
trigger: "item",
},
legend: {
orient: "vertical",
left: "left",
},
series: [
{
name: "数量",
type: "pie",
radius: "50%",
data: [
{ value: 1048, name: "测试用例1" },
{ value: 735, name: "测试用例2" },
{ value: 580, name: "测试用例3" },
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
},
],
},
四、页面效果和完整代码
① 示例效果
② 示例完整代码
<template>
<div>
<div id="echart" style="width: 100%; height: 300px"></div>
</div>
</template>
<script>
export default {
components: {},
data() {
return {
option: {
title: {
text: "测试用例",
left: "center",
},
tooltip: {
trigger: "item",
},
legend: {
orient: "vertical",
left: "left",
},
series: [
{
name: "数量",
type: "pie",
radius: "50%",
data: [
{ value: 1048, name: "测试用例1" },
{ value: 735, name: "测试用例2" },
{ value: 580, name: "测试用例3" },
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
},
],
},
};
},
created() {
},
methods: {
drawChart() {
const myChart = this.$echarts.init(document.getElementById("echart"));
myChart.setoption(this.option);
},
},
mounted() {
this.drawChart();
},
};
</script>
<style scoped lang="less">
</style>
五、可能的出错和解决方式
① Error: Initialize Failed: invalid dom.
将this.drawChart();放到了create里面,没放到mounted里
② Error in mounted hook: "ReferenceError: echarts is not defined"
没有正确引用echarts,特别是看看引用的那段是否出错,以及main.js中是否全局引用。
const myChart = this.$echarts.init(document.getElementById("echart"));
原文地址:https://www.jb51.cc/wenti/3280756.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。