先上代码,代码段里面有解释,方便解决自己日后忘记及萌新入门之用
//这是父组件
<template>
<div>
<echarts-pie
//echarts-pie为引入注册的驼峰式命名
ecname="总风险指数"
:ecnumber="Number(this.getIllnessByIdCardScore.sumRisk)">
//ecname和:ecnumber为想要传递给echarts子组件的值
</echarts-pie>
</div>
</template>
<script>
import EchartsPie from "@/components/EchartsPie.vue";
//引入
</script>
export default {
components: {
EchartsPie,
//注册echarts组件
},
data() {
return {
getIllnessByIdCardScore: {sumRisk:20},
//上文this.getIllnessByIdCardScore.risk实际为通过后端请求过来的赋值
}
}
下文为子组件echarts,本文的用法仅限于vue
<template>
<div ref="mychart" style="width: 384px; height: 389px">
//此处为给echarts规定了画布的大小
//如果一个页面有多个echarts建议使用此方法通过ref
</div>
</template>
<script>
export default {
props: {
ecname: {
type: String,
// 指定默认值
default: "未传值",
},
ecnumber: {
// 指定默认值
default: 0,
},
},
data() {
return {
//此处的ff为下文画布函数中的data数据,通过定义在这里方便监听
ff: [
{
value: this._props.ecnumber ? this._props.ecnumber : 0,
name: this._props.ecname,
},
{ value: 100, name: "" },
],
};
},
mounted() {
this.drawLine();
// console.log(this);
// console.log(this._props.eccolor)
// console.log(this)
},
//本次的是一个对比饼状图后端返回一个值,通过自定义函数计算出相对的值
computed: {
ecjian() {
//返回值为给对比值赋值
return (this.ff[1].value = 100 - this._props.ecnumber);
},
},
//开始监听
//因为开启了深度监听所以需要在handler函数中
//handler函数为固定的萌新记住就好
watch: {
//ecnumber是监听的对象
ecnumber: {
handler(newVal, oldVal) {//newVal为新传入数据,oldVal为当前数据或上一次
//此处给监听的对象加一个条件,防止空值进入
if (newVal !== undefined) {
this.ff[0].value = newVal;//当新值传入给echarts赋值
this.ecjian;//执行上文的计数函数,因为计算函数不能赋值给data,所以要在这里执行,让计算属性里面的逻辑结构执行
this.drawLine();//这是执行画布函数,结合上文的逻辑就是执行到这里让echarts重新绘制
}
},
deep: true,//深度监听开启
},
},
methods: {
drawLine() {
// 基于准备好的dom,初始化echarts实例
let myChart = this.$echarts.init(this.$refs.mychart);//这里用初始化使用refs创建echarts与上文一样为了一个页面绘制多个echarts图表,此图为饼状图
myChart.clear();//这里很重要,想要echarts再次绘制必须要有这个,作用是为了清空上一次的画布,如果不清空不能再次绘制而且会报错,真的很重要这里不能遗漏!!!!!!!!
// 绘制图表
myChart.setOption(
{
tooltip: {
trigger: "item",
show: false, // 关闭鼠标移上去后显示浮框信息
},
legend: {
top: "0%",
show: false,
left: "center",
},
title: {
// 图形标题(如果想要换行则使用ES6 `` 模板字符串)
// 例如: `示例
// 这里的文字会变为第二行(因为会保留格式)
// `
text: this.ff[0].value,
left: "center", //对齐方式居中
top: "55%", //距离顶部
textStyle: {
//文字配置
color: "#FF6C61", //文字颜色
fontSize: 20, //字号
align: "center", //对齐方式
},
},
series: [
{
// name: "Access From",
type: "pie",
radius: ["40%", "70%"],
avoidLabelOverlap: false,
label: {
// show: false,
position: "center",
fontSize: "20",
},
emphasis: {
label: {
show: true,
// fontSize: "20",
fontWeight: "bold",
},
},
labelLine: {
show: false,
},
itemStyle: {
//图形样式设置
normal: {
//第一种,这种就是在已知有多少数据项的情况下定义
color: function (params) {
//自定义饼图各板块颜色
var ec1color = "#F86359";
var colorList = [ec1color, "#EEEEEE"];//这里两个颜色可以按照需求添加多个颜色,进行颜色的自定义,个人需求只有两个数据所以只放了两个颜色
return colorList[params.dataIndex];
},
},
},
data: this.ff,//这里是上文data里面定义的数据
},
],
},
true
);
},
},
};
</script>
查询前效果图
查询后效果图