目前我遇到的情况就是用动态的二维数组数据渲染echarts图标,我们从后端收到的接口一般是个一维数组,需要手动构建并且保证响应式。接下来我做了个案例
一、案例总逻辑
1. 先创建一个vue项目
2. 添加 echarts依赖
3. 模拟数据请求,构建二维数组响应式数据,渲染图表
二、创建一个vite项目(也就是vue项目,但使用的是vite而不是webpack)
1.找到打开vite官网
2. 运行创建命令
yarn create vite
3. 执行yarn install安装项目依赖,之后执行行yarn dev运行项目
三、添加echarts依赖
1. 搜索echarts官网
2. 添加依赖
yarn add echarts
三、 模拟数据请求,构建二维数组响应式数据,渲染图表
这里有两个问题值得注意
1. 处理二维数组
2. 异步请求数据:我目前的解决办法是,等数据请求完成再渲染图标。 当然也有第二种方式,就是向渲染空表,等待数据过来后,再执行一次 setOption
<script setup>
import { ref, reactive, onMounted } from "vue";
import * as echarts from 'echarts';
let myChart;
let data = reactive([]);
onMounted(() => {//1. 初始化eharts的渲染节点const chartDom = document.getElementById("boxEcharts");myChart = echarts.init(chartDom);//2. 获取数据(模拟请求数据是异步的)setTimeout(()=>{/*目标数据格式[["score", "amount", "product"],[89.3, 58212, "Matcha Latte"],[57.1, 78254, "Milk Tea"],[74.4, 41032, "Cheese Cocoa"],[50.1, 12755, "Cheese Brownie"],[89.7, 20145, "Matcha Cocoa"],[68.1, 79146, "Tea"],[19.6, 91852, "Orange Juice"],[10.6, 101852, "Lemon Juice"],[32.7, 20112, "Walnut Brownie"],]*///请求回来的数据是一维对象数组let d1 = [{score: "score",amount: "amount",product: "product"},{score: 89.3,amount: 58212,product: "Matcha Latte"},{score: 57.1,amount: 78254,product: "Milk Tea"},{score: 74.4,amount: 41032,product: "Cheese Cocoa"}];/*处理成二维数组*/let arr = []; //定义一个数组,让它里面直接装数组d1.forEach(item=>{arr.push([item.score,item.amount,item.product]);});data.push(...arr); //将这个二维数组解构为 一维数组放进 定义好的响应数组中renderEcharts();},1500)
});//3. 渲染图表
const renderEcharts = () => {const option = {dataset: {source: data,},grid: { containLabel: true },xAxis: { name: "amount" },yAxis: { type: "category" },visualMap: {orient: "horizontal",left: "center",min: 10,max: 100,text: ["High Score", "Low Score"],// Map the score column to colordimension: 0,inRange: {color: ["#65B581", "#FFCE34", "#FD665F"],},},series: [{type: "bar",encode: {// Map the "amount" column to X axis.x: "amount",// Map the "product" column to Y axisy: "product",},},],};option && myChart.setOption(option,true);
};
</script><template><div id="boxEcharts"></div>
</template><style scoped>
#boxEcharts{width: 40vw;height: 40vh;
}
</style>