【echarts入门】:vue项目中应用echarts

一.安装echarts

在项目集成终端下载echarts

javascript 复制代码
npm install echarts --save

二.全局引入

创建/components/echarts/index.js

javascript 复制代码
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from "echarts/core";

/** 引入任意图表,这里引入的是柱状图and折线图图表(图表后缀都为 Chart)  */
import { BarChart, LineChart } from "echarts/charts";

// 引入提示框,标题,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
} from "echarts/components";

// 标签自动布局,全局过渡动画等特性
import { LabelLayout, UniversalTransition } from "echarts/features";

// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from "echarts/renderers";

// 注册必须的组件
echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    BarChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer,
    LineChart,
]);

// 导出
export default echarts;

在main.js注册

javascript 复制代码
import echarts from "./components/echarts/index.js";

Vue.prototype.$echarts = echarts;

在组件中使用

html 复制代码
<template>
    <div>
        <div id="maychar" style="width: 100%; height: 400px;"></div>
    </div>
</template>
   
<script>
export default {
    data () {
        return {};
    },
    mounted () {
        this.getCharts();
    },
    methods: {
        // 使用柱形图,关于其他配置可以去官网查看
        getCharts () {
            const chartBox = this.$echarts.init(document.getElementById("maychar"));
            const option = {
                xAxis: {
                    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
                },
                yAxis: {},
                series: [
                    {
                        type: "bar",
                        data: [23, 24, 18, 25, 27, 28, 25],
                    },
                ],
            };
            chartBox.setOption(option);
            // 根据页面大小自动响应图表大小
            window.addEventListener("resize", function () {
                chartBox.resize();
            });
        },
    },
};
</script>
相关推荐
子兮曰6 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭6 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路8 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒10 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
lemon_yyds10 小时前
《vue 2 升级vue3 父组件 子组件 传值: value 和 v-model
vue.js
Kagol11 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉11 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau11 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生11 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼11 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范