9、vue_echarts
安装及导入
npm install echarts --save
import * as echarts from "echarts";
定义echarts容器
<template> <div ref="chartDom" :style="{ width: '100%', height: '70%' }"></div> </template>
初始化echarts并渲染数据
<script setup> import { ref, onMounted } from "vue"; import * as echarts from "echarts"; // 定义ref const chartDom = ref(); // 挂载dom元素,否则不渲染 onMounted(() => { // echarts的放到onMounted(()=>{})中 initchart(); window.onresize = function () { myChart.resize(); //自适应大小 }; }); // 初始化并绘制图表 const initchart = () => { // 初始化echarts(基于挂载的dom) var myChart = echarts.init(chartDom.value); // echarts数据 var option = { title: { text: "ECharts 入门示例", }, xAxis: { data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], }, yAxis: {}, series: [ { name: "金额", type: "bar", data: [5, 20, 36, 10, 10, 20], }, ], }; // 绘制echarts myChart.setOption(option); }; </script>
异步获取后台数据
<template> <div ref="chartDom" :style="{ width: '100%', height: '70%' }"></div> </template> <script setup> import { ref, onMounted } from "vue"; import * as echarts from "echarts"; import { $sale } from "../api/sale"; // 定义ref const chartDom = ref(); // 挂载dom元素,否则不渲染 onMounted(() => { getData(); //异步数据改为挂载getData window.onresize = function () { myChart.resize(); //自适应大小 }; }); // 异步获取后台数据,把渲染和初始化放到axios.then()里面,避免渲染空数据 const getData = async () => { await $sale().then((res) => { // console.log(res.data); let a = res.data.map((x) => x.yearmonth); let b = res.data.map((x) => x.taxamount); // 将后台数据传递给echarts initchart(res.data); }); }; // 初始化并绘制图表 const initchart = (str) => { // 接收后台传来的数据初始化echarts(基于挂载的dom) var myChart = echarts.init(chartDom.value); // echarts数据 var option = { title: { text: "ECharts 入门示例", }, xAxis: { data: str.map((x) => x.yearmonth), }, yAxis: {}, series: [ { name: "金额", type: "bar", data: str.map((x) => x.taxamount), }, ], }; // 绘制echarts myChart.setOption(option); }; </script>