1 Star 1 Fork 0

Zen/vue3-echarts-demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

Vue 3+ECharts Demo

一个 Vue 3+ECharts 的 Demo, 效果如下:

img

项目初始化

> npm create vite@latest

该项目主要用到的库

  • echarts
  • tailwindcss
  • normalize.css
  • vue-router
  • NaiveUI
  • VueX

安装方式如下:

  1. 安装 echarts
> npm install echarts
  1. 安装 tailwindcss
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p

创建 index.css 文件

@tailwind base;
@tailwind components;
@tailwind utilities;

main.js 中进行引用

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

createApp(App).mount('#app')
  1. 安装 normalize.css
> npm install --save normalize.css
  1. 安装 vue-router
> npm install vue-router@4

组件中 Echarts 图表的使用


<template>
    <div ref="mychart" style="width: 450px; height: 350px;">
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
// 引入 Echarts
import * as echarts from 'echarts'

//导入 option 数据
import pie from '@/assets/data/pie'
//获取 Dom 元素
const mychart = ref(null)
onMounted(() => {
    // 基于准备好的dom,初始化echarts实例
    let mycharts = echarts.init(mychart.value)
    // 绘制图表
    mycharts.setOption(pie)
})

</script>

<style lang="less" scoped>
</style>

其中 option 数据可单独包存在一个 js 文件中,也可以直接插入到组件代码中,如下:

<script setup>
  import { ref, onMounted } from "vue";
  import * as echarts from "echarts";

  /* 通过 ref 获取 Dom 元素: 【通过 ref 获取 DOM元素【Vue3 Composition API】】
https://www.bilibili.com/video/BV1Uq4y1L7oj/?share_source=copy_web&vd_source=11797d2715355519fb920653c1a14e31 */
  const mychart = ref(null);

  onMounted(() => {
    console.log(mychart.value);
    let mycharts = echarts.init(mychart.value);
    let option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b} : {c} ({d}%)",
      },
      series: [
        {
          type: "gauge",
          axisLine: {
            lineStyle: {
              width: 30,
              color: [
                [0.3, "#67e0e3"],
                [0.7, "#37a2da"],
                [1, "#fd666d"],
              ],
            },
          },
          pointer: {
            itemStyle: {
              color: "inherit",
            },
          },
          axisTick: {
            distance: -30,
            length: 8,
            lineStyle: {
              color: "#fff",
              width: 2,
            },
          },
          splitLine: {
            distance: -30,
            length: 30,
            lineStyle: {
              color: "#fff",
              width: 4,
            },
          },
          axisLabel: {
            color: "inherit",
            distance: 40,
            fontSize: 10,
          },
          detail: {
            valueAnimation: true,
            formatter: "{value} km/h",
            color: "inherit",
          },
          data: [
            {
              name: "Speed",
              value: 70,
              detail: {
                fontWeight: "normal",
                fontSize: 22,
              },
            },
          ],
        },
      ],
    };
    setInterval(function () {
      mycharts.setOption({
        series: [
          {
            data: [
              {
                name: "Speed",
                value: +(Math.random() * 100).toFixed(2),
                detail: {
                  fontWeight: "normal",
                  fontSize: 22,
                },
              },
            ],
          },
        ],
      });
    }, 2000);
    mycharts.setOption(option);
    // 图表大小自适应
    window.addEventListener("resize", function () {
      mycharts.resize();
    });
  });
</script>

增加了登录功能

输入用户名 admin 与密码 1234 将跳转至主界面

Bug

  • edge 浏览器死活加载不出来,但是 Firefox 浏览器能 (终究是被我解决了)
  • 登录功能东拼西凑勉强有效果,但是受限于个人能力,代码写的及其丑陋,并且存在严重的逻辑漏洞,需要在后面完善

2 月 15 日更新

  1. home 界面重构,增加了退出登录按钮

2 月 16 日更新

增加了 Side Menu,新的 demo 如下:

文件上传下载功能

前端代码

文件上传:

<n-upload
  action="/api/upload"
  list-type="image"
  v-model:file-list="fileList"
  show-download-button
  :create-thumbnail-url="createThumbnailUrl"
  @download="handleDownload"
>
  <n-button>上传文件</n-button>
</n-upload>

文件下载:

function handleDownload(file) {
  console.log(file.name);
  downloadFile(file.name).then((res) => {
    if (res.status == 200) {
      // 文件下载功能
      const blob = new Blob([res.data]);
      const downloadElement = document.createElement("a");
      const href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = file.name;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
      message.success(`下载成功:${file.name}`);
    }
  });
}

界面布局

消息弹窗&对话框

  1. 修改 App.vue文件如以下格式:

<script setup>
</script>

<template>

  <n-dialog-provider>
    <n-message-provider>
      <router-view></router-view>
    </n-message-provider>
  </n-dialog-provider>
  <!-- <router-view></router-view>7 -->
</template>

<style scoped>

</style>

其中最终要的是在 代码中添加 <n-dialog-provider></n-dialog-provider> 标签与 <n-message-provider></n-message-provider> 标签

  1. 添加完成之后就可以在任意界面中进行使用了,实例如下:

<!-- 新功能探索界面 -->
<template>
  <n-button @click="handleConfirm">
    警告
  </n-button>
</template>

<script setup>
import { useDialog, useMessage } from 'naive-ui'
const dialog = useDialog();
const message = useMessage();
function handleConfirm() {
  dialog.warning({
    title: "警告",
    content: "你确定?",
    positiveText: "确定",
    negativeText: "不确定",
    onPositiveClick: () => {
      message.success("确定");
    },
    onNegativeClick: () => {
      message.error("不确定");
    }
  });
}
</script>

<style lang="scss" scoped></style>

Bug

  • 上传带有中文文件名的文件会乱码

听说用 decodeURI() 可以解决 主要是后台的原因,修改 mock/index.js代码如下:

let uploading = multer({
  dest: "./mock/upload",
  // 设定限制,每次最多上传1个文件,文件大小不超过1MB
  limits: { fileSize: 10000000, files: 1 },
  fileFilter(req, file, callback) {
    // 解决中文名乱码的问题
    // latin1 是一种编码格式
    file.originalname = Buffer.from(file.originalname, "latin1").toString(
      "utf8"
    );
    callback(null, true);
  },
})
  • 文件上传后页面中的文件列表在网页刷新后会消失

利用 Git 将项目 down 下来

当然也可以直接下载压缩包

  1. 一台新的PC需要先安装 Git
  2. 将项目forck到你的账户下
  3. 在 设置->安全设置 添加生成的 ssh 公钥
  4. 将项目克隆下来 git clone git@gitee.com:code_from_qh/vue3-echarts-demo.git
  5. 用如下命令配置 git 的用户名与邮箱
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
  1. 利用 Vscode 内置的 Source Control 功能暂存、提交与同步代码

如何将代码跑起来

  1. 安装 Node.js
  2. 将项目下的 package-lock.json文件与node_modules文件夹删除(根目录下和/mock/目录下都有)
  3. 在根目录下和/mock/目录下分别执行 cnpm install
  4. 在 Terminal 中执行命令 npm run dev

cnpm 的安装方式:npm install cnpm -g --registry=https://registry.npm.taobao.org

MIT License Copyright (c) 2023 Zen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

在 vue3 中使用 echarts 的 demo 展开 收起
README
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/code_from_qh/vue3-echarts-demo.git
git@gitee.com:code_from_qh/vue3-echarts-demo.git
code_from_qh
vue3-echarts-demo
vue3-echarts-demo
master

搜索帮助