创建Vue2项目,引入chart.js,并生成柱形图、折线图、饼图

基础创建

1. 创建一个新的 Vue 2 项目

如果你还没有创建项目,可以使用 Vue CLI 来创建一个新项目。首先确保你已经安装了 Node.js 和 npm。然后安装 Vue CLI 并创建一个新项目。

npm install -g @vue/cli
vue create my-vue-chart-project

在创建过程中选择 Vue 2 版本。

image-20231207132032993

2. 安装 Chart.js 库

进入项目目录,通过 npm 或 yarn 安装 Chart.js 库。

cd my-vue-chart-project
npm install chart.js@2.9.4 --save # 安装适用于 Vue 2 的 Chart.js 版本

柱形图

3. 创建 BarChart 组件(柱形图)

src/components 目录下创建一个新的 Vue 组件 BarChart.vue

<template>
  <div>
    <canvas id="bar-chart"></canvas>
  </div>
</template>

<script>
import Chart from 'chart.js';

export default {
  name: 'BarChart',
  props: {
    data: {
      type: Array,
      required: true
    },
    labels: {
      type: Array,
      required: true
    },
    title: {
      type: String,
      required: true
    },
  },
  mounted() {
    this.createBarChart();
  },
  methods: {
    createBarChart() {
      const ctx = document.getElementById('bar-chart').getContext('2d');
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: this.labels,
          datasets: [{
            label: this.title,
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderColor: 'rgba(255, 99, 132, 1)',
            borderWidth: 1,
            data: this.data
          }]
        },
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      });
    }
  }
};
</script>

这个组件接收两个 prop:datalabels,分别表示柱形图的数据和标签。

4. 在父组件中使用 BarChart 组件

首先,你需要在父组件(例如 App.vue)中导入 BarChart 组件,并注册它。

<template>
  <div id="app">
    <div style="width:45%; margin-bottom: 20px;margin-left: 20px;">
      <bar-chart :data="chartData1" :labels="chartLabels1" :title="title1" />
    </div>
  </div>
</template>

<script>
import BarChart from './components/BarChart.vue';

export default {
  name: 'App',
  components: {
    BarChart
  },
  data() {
    return {
      chartLabels1: ['January', 'February', 'March', 'April', 'May', 'June', 'July','Auguest','September','October','November','December'],
      chartData1: [0, 10, 5, 2, 20, 30, 45,60,65,75,85,100],
      title1: '柱形图'
    };
  }
};
</script>

在这里,我们定义了 chartData1chartLabels1,然后将它们传递给 BarChart 组件。

5. 运行项目

现在,你可以启动项目来查看柱形图。

npm run serve

访问浏览器中的项目地址(通常是 http://localhost:8080),你应该能够看到你的柱形图。

image-20231207131002993

最后根据你的需求,将后端数据放到chartLabels与chartData中即可

折线图

6.创建LineChart组件(折线图)

创建一个组件用于显示折线图: 在src/components目录下创建一个新的组件文件LineChart.vue,并在其中编写以下代码

<template>
  <div>
    <canvas id="line-chart" ref="chart"></canvas>
  </div>
</template>

<script>
import Chart from 'chart.js';

export default {
  name: 'LineChart',
  props: {
    data: {
      type: Array,
      required: true
    },
    labels: {
      type: Array,
      required: true
    },
    title: {
      type: String,
      required: true
    }
  },
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      const ctx = this.$refs.chart.getContext('2d');
      new Chart(ctx, {
        type: 'line',
        data: {
          labels: this.labels,
          datasets: [{
            label: this.title,
            data: this.data,
            fill: false,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.1
          }]
        },
        options: {
          // responsive: true,
          // maintainAspectRatio: false,
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      });
    }
  }
};
</script>

<style scoped>
canvas {
  max-width: 600px;
  margin: 0 auto;
}
</style>

7.在App.vue中使用折线图组件

打开src/App.vue文件,并进行以下修改:

<template>
  <div id="app">
    <div style="width:45%;margin-bottom: 20px;margin-left: 20px;">
      <LineChart :data="chartData2" :labels="chartLabels2" :title="title2" />
    </div>
  </div>
</template>

<script>
import LineChart from './components/LineChart.vue';

export default {
  name: 'App',
  components: {
    LineChart
  },
  data() {
    return {
      chartLabels2: ['January', 'February', 'March', 'April', 'May', 'June', 'July','Auguest','September','October','November','December'],
      chartData2: [0, 10, 5, 2, 20, 30, 45,60,65,75,85,100],
      title2: '折线图'
    };
  }
};
</script>
<style>
#app {
  text-align: center;
}
</style>

8.运行项目:

在终端中执行以下命令启动项目:

npm run serve

等待编译完成后,在浏览器中访问http://localhost:8080(或其他指定的端口),即可看到显示了折线图的页面。

这样,你就成功地在Vue 2.x项目中引入了Chart.js,并生成了一个简单的折线图。你可以根据自己的需求进一步配置和美化图表。

image-20231207121534879

饼图

9.创建PieChart组件用于显示饼图

在src/components目录下创建一个新的组件文件PieChart.vue,并在其中编写以下代码:

<template>
  <div>
    <canvas id="pie-chart"></canvas>
  </div>
</template>

<script>
import Chart from 'chart.js';

export default {
  name: 'PieChart',
  props: {
    data: {
      type: Array,
      required: true
    },
    labels: {
      type: Array,
      required: true
    },
    title: {
      type: String,
      required: true
    }
  },
  mounted() {
    this.createBarChart();
  },
  methods: {
    createBarChart() {
      const ctx = document.getElementById('pie-chart').getContext('2d');
      new Chart(ctx, {
        type: 'pie',
        data: {
          labels: this.labels,
          datasets: [{
            label: this.title,
            backgroundColor: [
              'rgb(127,255,212)',
              'rgb(255,0,0)',
              'rgb(255, 99, 132)',
              'rgb(0,255,0)',
              'rgb(54, 162, 235)',
              'rgb(255, 205, 86)',
              'rgb(0,255,255)',
              'rgb(255,255,0)',
              'rgb(8,46,84)',
              'rgb(106,90,205)',
              'rgb(54,94,15)',
              'rgb(255,0,255)'
            ],
            borderColor: [
            'rgb(127,255,212)',
              'rgb(255,0,0)',
              'rgb(255, 99, 132)',
              'rgb(0,255,0)',
              'rgb(54, 162, 235)',
              'rgb(255, 205, 86)',
              'rgb(0,255,255)',
              'rgb(255,255,0)',
              'rgb(8,46,84)',
              'rgb(106,90,205)',
              'rgb(54,94,15)',
              'rgb(255,0,255)'
            ],
            borderWidth: 1,
            data: this.data
          }]
        },
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      });
    }
  }
};
</script>

10.在App.vue中使用饼图组件

打开src/App.vue文件,并进行以下修改:

<template>
  <div id="app">
    <div style="width:45%; margin-bottom: 20px;margin-left: 20px; margin-top: 20px">
      <PieChart :data="chartData3" :labels="chartLabels3" :title="title3"  />
    </div>
  </div>
</template>

<script>
import PieChart from './components/PieChart.vue';

export default {
  name: 'App',
  components: {
    PieChart
  },
  data() {
    return {
      chartLabels3: ['January', 'February', 'March', 'April', 'May', 'June', 'July','Auguest','September','October','November','December'],
      chartData3: [0, 10, 5, 2, 20, 30, 45,60,65,75,85,100],
      title3: '饼图'
    };
  }
};
</script>
<style>
#app {
  text-align: center;
}
</style>

11.运行项目:

在终端中执行以下命令启动项目:

npm run serve

等待编译完成后,在浏览器中访问http://localhost:8080(或其他指定的端口),即可看到显示了饼图的页面。

这样,你就成功地在Vue 2.x项目中引入了Chart.js,并生成了一个简单的饼图。你可以根据自己的需求进一步配置和美化图表。

image-20231207131842584

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/231689.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

End-to-End Reconstruction-Classification Learning for Face Forgery Detection

一、研究背景 现有模型主要通过提取特定的伪造模式进行深度伪造检测&#xff0c;导致学习到的表征与训练集中已知的伪造类型高度相关&#xff0c;因此模型难以泛化到未知的伪造类型上使用。 二、研究动机 1.真实样本的特征分布相对更为紧凑&#xff0c;因此学习真实人脸之间的…

【GEE】时间序列多源遥感数据随机森林回归预测|反演|验证|散点图|完整代码

实验介绍 分类和回归之间的主要区别在于&#xff0c;在分类中&#xff0c;我们的预测目标是离散的类别&#xff0c;而在回归中&#xff0c;预测目标是连续的预测值。 本实验的研究区域位于佛蒙特州的埃塞克斯郡&#xff0c;使用训练数据来模拟土壤氧化还原深度&#xff0c;然…

Chart 7 内存优化

文章目录 前言7.1 Adreno GPU OpenCL内存7.1.1 内存声明周期7.1.2 Loacl Memory7.1.3 Constant memory(常量内存)7.1.4 Private Memory7.1.5 Global Memory7.1.5.1 Buffer Object7.1.5.2 Image Object7.1.5.3 Image object vs. buffer object7.1.5.4 Use of both Image and buf…

基于Python+Django+mysql图书管理系统

基于PythonDjangomysql图书管理系统 一、系统介绍二、功能展示三、其它系统四、获取源码 一、系统介绍 程序开发软件&#xff1a;Pycharm 数据库&#xff1a;mysql 采用技术&#xff1a; Django(一个MVT框架&#xff0c;类似Java的SSM框架) 人生苦短&#xff0c;我用Python&a…

【Vue】日常错误总结(持续更新)

日常遇到的小问题汇总, 内容小篇幅少的就全放这里了, 内容多的会在Vue专栏单独分享~ 目录 【Q】 el-form-item值为 null 或 undefined显示““ 【Q】dialog内组件数据刷新总是延迟慢一拍 问题背景描述 解决方案 代码简单模拟 JS 【Q】el-input 不能输入的解决办法 方法…

LeetCode008之字符串转换整数 (相关话题:状态机)

题目描述 请你来实现一个 myAtoi(string s) 函数&#xff0c;使其能将字符串转换成一个 32 位有符号整数&#xff08;类似 C/C 中的 atoi 函数&#xff09;。 函数 myAtoi(string s) 的算法如下&#xff1a; 读入字符串并丢弃无用的前导空格检查下一个字符&#xff08;假设还…

TailwindCSS 支持文本文字超长溢出截断、文字文本省略号

前言 文本文字超长截断并自动补充省略号&#xff0c;这是前端日常开发工作中常用的样式设置能力&#xff0c;文字超长截断主要分为单行超长截断和多行超长截断。本文通过介绍基本CSS样式、tailwindcss 类设置两种基础方式来实现文字超长截断。 TailwindCSS 设置 单行文字超长…

编写Yaml文件当Poc,利用Nuclei扫描器去扫描漏洞

编写Yaml文件当Poc,利用Nuclei扫描器去扫描漏洞 YAML是一种数据序列化语言&#xff0c;它的基本语法规则注意如下&#xff1a; -大小写敏感 -使用缩进表示层级关系 -缩进时不允许使用Tab键&#xff0c;只允许使用空格。 -缩进的空格数目不重要&#xff0c;只要相同层级的元…

springboot_ssm_java学位论文盲审系统

本系统主要实现用户登录验证&#xff0c;用户使用邮箱&#xff0c;密码和选择身份进行登录&#xff0c;用户查看个人中心&#xff0c;提交论文&#xff0c;发表留言和问题反馈。用户在线注册。学生模块功能实现&#xff1a;学生注册&#xff0c;查看信息&#xff0c;修改资料&a…

C++新经典模板与泛型编程:将trait类模板用作模板参数

将trait类模板用作模板参数 template<typename T> struct SumFixedTraits;template<> struct SumFixedTraits<char> {using sumT int;static sumT initValue() {return 0;} };template<> struct SumFixedTraits<int> {using sumT __int64;sta…

2023年 - 我的程序员之旅和成长故事

2023年 - 我的程序员之旅和成长故事 &#x1f525; 1.前言 大家好&#xff0c;我是Leo哥&#x1fae3;&#x1fae3;&#x1fae3;&#xff0c;今天咱们不聊技术&#xff0c;聊聊我自己&#xff0c;聊聊我从2023年年初到现在的一些经历和故事&#xff0c;我也很愿意我的故事分…

力扣:199. 二叉树的右视图(Python3)

题目&#xff1a; 给定一个二叉树的 根节点 root&#xff0c;想象自己站在它的右侧&#xff0c;按照从顶部到底部的顺序&#xff0c;返回从右侧所能看到的节点值。 来源&#xff1a;力扣&#xff08;LeetCode&#xff09; 链接&#xff1a;力扣&#xff08;LeetCode&#xff09…

Error: Cannot find module ‘E:\Workspace_zwf\mall\build\webpack.dev.conf.js‘

执行&#xff1a;npm run dev E:\Workspace_zwf\zengwenfeng-master>npm run dev> mall-app-web1.0.0 dev E:\Workspace_zwf\zengwenfeng-master > webpack-dev-server --inline --progress --config build/webpack.dev.conf.jsinternal/modules/cjs/loader.js:983thr…

PyQt6 QTimeEdit时间控件

​锋哥原创的PyQt6视频教程&#xff1a; 2024版 PyQt6 Python桌面开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 PyQt6 Python桌面开发 视频教程(无废话版) 玩命更新中~共计39条视频&#xff0c;包括&#xff1a;2024版 PyQt6 Python桌面开发 视频教程(无废话…

微表情检测(三)----基于光流特征的微表情检测

Micro-expression spotting based on optical flow features 基于光流特征的微表情检测 Abstract 本文提出了一种高精度和可解释性的自动微表情检测方法。首先&#xff0c;我们设计了基于鼻尖位置的图像对齐方法&#xff0c;以消除由头部晃动引起的全局位移。其次&#xff0…

扁平按钮样式

上图 代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>扁平按钮</title><style>body {margin: 0;padding: 0;height: 100vh;display: flex;justify-content: center;ali…

【论文笔记】FastPillars: A Deployment-friendly Pillar-based 3D Detector

原文链接&#xff1a;https://arxiv.org/abs/2302.02367 1. 引言 目前基于激光雷达的主流方法分为基于点云的方法和基于体素的方法。前者能保留最多的几何信息&#xff0c;但点查询和遍历耗时&#xff1b;后者使用3D/2D卷积处理体素化点云&#xff0c;但用于提高效率的3D稀疏…

mysql面试题——MVCC

一&#xff1a;什么是MVCC&#xff1f; 多版本并发控制&#xff0c;更好的方式去处理读-写冲突&#xff0c;就是为了查询一些正在被另一个事务更新的行&#xff0c;并且可以看到它们被更新之前的值&#xff0c;这样在做查询的时候就不用等待另一个事务释放锁。 二&#xff1a…

webrtc网之sip转webrtc

OpenSIP是一个开源的SIP&#xff08;Session Initiation Protocol&#xff09;服务器&#xff0c;它提供了一个可扩展的基础架构&#xff0c;用于建立、终止和管理VoIP&#xff08;Voice over IP&#xff09;通信会话。SIP是一种通信协议&#xff0c;用于建立、修改和终止多媒体…

【Python】 生成二维码

创建了一个使用 python 创建二维码的程序。 下面是生成的程序的图像。 功能描述 输入网址&#xff08;URL&#xff09;。 输入二维码的名称。 当单击 QR 码生成按钮时&#xff0c;将使用 QRname 中输入的字符将 QR 码生成为图像。 程序代码 import qrcode import tkinterd…
最新文章