0
点赞
收藏
分享

微信扫一扫

学完Echarts,来个大项目练手(用到vue koa2 echarts技术)

尤克乔乔 2022-06-01 阅读 103

文章目录


在这里插入图片描述

Echarts大项目

前言

1.所用技术详解

1.1 vue技术

在使用这个技术的过程中,主要是用到关于组件的创建,以及路由的使用。以及在
组件中创建各种方法,用于处理数据。
所以说,在上手这个项目时,你应该对于vue有一定的基础。vue官网

1.2 Echarts技术

关于这个,你需要有一点入门的基础,可以Echarts入门参考这篇文章
那么在这个项目中主要是创建饼图,柱状图,地图,折线图。
所以说你需要了解关于他们怎么创建,以及配置效果

1.3 koa2技术

koa2技术与express是由同一个技术团队推出的,效果与express相同。
那么如果你有一定的express基础的话,那么koa2就计较简单了。
你可以参考这篇文章5分钟入手熟悉express
在koa2技术中主要是搭建本地服务器(后台)用于读取相关的本地文件数据,
进行格式转换,创建接口,用于在前台访问接口并获取数据

2.后台的搭建

2.1需要实现的效果

  1. 根据URL读取指定目录下的文件内容

2.2效果实现

2.2.1搭建koa2基本架构

  • 安装
  • 创建基本代码
const koa=require("koa")
const app=new koa()
app.listen(8888)
  • 目录结构
    在这里插入图片描述

2.2实现代码

  • koa_response_data.js
// 处理业务逻辑的中间件,读取某个json文件的数据
const path = require('path')
const fileUtils = require('../utils/file_utils')
module.exports = async (ctx, next) => {
 // 根据url
 const url = ctx.request.url // /api/seller  ../data/seller.json
 let filePath = url.replace('/api', '') // /seller
 filePath = '../data' + filePath + '.json'  // ../data/seller.json
 filePath = path.join(__dirname, filePath)
 try {
  const ret = await fileUtils.getFileJsonData(filePath)
  ctx.response.body = ret
file_utils.js
5.允许跨域
设置响应头
} catch (error) {
  const errorMsg = {
   message: '读取文件内容失败, 文件资源不存在',
   status: 404
 }
  ctx.response.body = JSON.stringify(errorMsg)
}
 console.log(filePath)
 await next()
}
  • file_utils.js
// 读取文件的工具方法
const fs = require('fs')
module.exports.getFileJsonData = (filePath) => {
 // 根据文件的路径, 读取文件的内容
 return new Promise((resolve, reject) => {
  fs.readFile(filePath, 'utf-8', (error, data) => {
   if(error) {
    // 读取文件失败
    reject(error)
  } else {
    // 读取文件成功
    resolve(data)
  }
 })
})
}
  • koa_response_header.js(用于设置访问解决跨域)
module.exports = async (ctx, next) => {
  const contentType = 'application/json; charset=utf-8'
  ctx.set('Content-Type', contentType)
  ctx.set("Access-Control-Allow-Origin", "*")
  ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE")
  await next()
}
  • app.js
// 服务器的入口文件
// 1.创建KOA的实例对象
const Koa = require('koa')
const app = new Koa()
// 2.绑定中间件
const respDataMiddleware = require('./middleware/koa_response_data')
app.use(respDataMiddleware)
// 3.绑定端口号 8888
app.listen(8888)
  • data中的json数据,我会放在评论区
    构

2.3最终效果显示

732

3.前端项目搭建

3.1下载vue-cli并创建一个柱状图

3.1.1利用vue-cli搭建项目

删除无关的代码。

  • 修改 App.vue 中的代码,将布局和样式删除, 变成如下代码:
<template>
 <div id="app">
  <router-view/>
 </div>
</template>
<style lang="less">
</style>
  • 删除 components/HelloWorld.vue 这个文件
  • 删除 views/About.vue 和 views/Home.vue 这两个文件
  • 修改 router/index.js 中的代码,去除路由配置和 Home 组件导入的代码
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = []
const router = new VueRouter({
 routes
})
export default router

3.1.2配置echart和axios

  • echarts配置
    在main.js中加入
// 将全局echarts对象挂载到Vue的原型对象上
Vue.prototype.$echarts = window.echarts

在public中引入echarts(echarts是下载好的,放在public文件先static的lib文件下)
在index.html中引入就可以了。

  • echarts使用
  • axios的引入及配置(在main.js中配置)
import axios from 'axios'
// 请求基准路径的配置
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/'
// 将axios挂载到Vue的原型对象上
// 在别的组件中 this.$http
Vue.prototype.$http = axios
  • axios的使用

4.开发一个单页面效果图(柱状图)

954

4.1在src文件夹下创建view和compent文件夹。

在创建的两个文件夹下分别创建SellerPage.vue(用于承接Seller.vue的效果)和seller.vue

  • 将SellerPage.vue和seller.vue配置在路由中
  • sellerPage.vue
<template>
<div class="com-page">
  <seller/>
</div>
</template>
<script>
//引入Seller组件
import Seller from '../components/Seller.vue'
export default {
  methods:{  
  },
  //将组件配置在sellerPage中
  components:{
    seller: Seller,
}  
}
</script>
<style>
</style>
  • router文件夹下的index.js
import  from '../view/SellerPage.vue'
const routes = [
  {
    path: '/sellerpage',
    component: SellerPage
  },
]
  • 在App.vue中
<template>
<div id="app">
  //占位符号
  <router-view></router-view>
</div>
</template>
import SellerPage from './view/SellerPage.vue';
export default {
    name: "App",
    components: {
       SellerPage
       }
}
  • Seller.vue加入
<template>
 <div class="com-container">
 Seller组件
  <div class="com-chart"></div>
 </div>
</template>

4.2书写实现柱状图的代码

4.2.1搭建基本架构

//seller.vue
export default {
  data() {
    return {
    }
  },
  mounted() {
  //调用 initCharts
    this.initCharts()
    this.getDate()
    //监听屏幕尺寸大小的改变
    window.addEventListener('resize', this.updataScreen)
    this.updataScreen()
  },
  destroyed() {
    //移除监听屏幕尺寸大小的改变
    window.removeEventListener('resize', this.updataScreen)
  },
  methods: {
  //初始化echart对象
    initCharts() {
      this.echartsInstance = this.$echarts.init(this.$refs.seller_ref, 'chalk')
      const initOption = {
      }
      this.echartsInstance.setOption(initOption)
    },
    //获取后台数据
   getDate() {
    },
    updataEchart() { 
    },
    //调整效果图的文字大小及图形自适应改变
    updataScreen() {
    	//设置字体大小
      const titleFontsize = this.$refs.seller_ref.offsetWidth / 100 * 3.6
      const upscreenOption = {
      }
      this.echartsInstance.setOption(upscreenOption)
      this.echartsInstance.resize()
    }
  }
}

4.2.2需要实现的功能

export default {
  data() {
    return {
      echartsInstance: null,
      allDate: null,
      //标记当前页数
      currentPage: 1,
     //记录总页数
      totalPage: 0,
      //标记定时器用于,在适当的时期,取消定时器
      timeid: null
    }
  },
  mounted() {
    this.initCharts()
    this.getDate()
    window.addEventListener('resize', this.updataScreen)
    this.updataScreen()
  },
  destroyed() {
    clearInterval(this.timeid)
    window.removeEventListener('resize', this.updataScreen)
  },
  methods: {
    initCharts() {
      this.echartsInstance = this.$echarts.init(this.$refs.seller_ref, 'chalk')
      //配置初始化option
      const initOption = {
        grid: {
          top: '15%',
          left: '3%',
          right: '6%',
          bottom: '3%',
          containLabel: true
        },
        title: {
          text: '💛 商家销售表'
        },
        tooltip: {
          show: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category'
        },
        series: {
          type: 'bar',
          label: {
            show: true,
            position: 'right',
            textStyle: {
              color: "white"
            },
          },
          itemStyle: {
            barBorderRadius: [0, 33, 33, 0],
            color: new this.$echarts.graphic.LinearGradient(0, 0, 1, 0, [
              // 百分之0状态之下的颜色值
              {
                offset: 0,
                color: '#5052EE'
              },
              // 百分之100状态之下的颜色值
              {
                offset: 1,
                color: '#AB6EE5'
              }
            ])
          }
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              show: true
            },
            restore: {
              show: true
            },
            dataView: {
              show: true
            },
            dataZoom: {
              show: true
            },
            magicType: {
              show: true,
              type: ['line', 'bar']
            }
          },
          iconStyle: {
            color: "skyblue",
          },
          top: 20,
          right: 100,
          itemGap: 20,
          itemSize: 20
        },
      }
      this.echartsInstance.setOption(initOption)
    },
    //配置数据化option
    async getDate() {
      const { data: ret } = await this.$http.get('seller')
      this.allDate = ret.sort((a, b) => {
        return a.value - b.value
      })
      this.totalPage = this.allDate.length % 5 === 0 ? parseInt(this.allDate.length / 5) : parseInt(this.allDate.length / 5) + 1
      this.updataEchart()
      this.startIntever()
    },
    //配置屏幕尺寸大小改变后的效果显示
    updataEchart() {
      const start = (this.currentPage - 1) * 5
      const end = this.currentPage * 5
      const showDate = this.allDate.slice(start, end)
      const xAxisArr = showDate.map(item => {
        return item.value
      })
      const yAxisArr = showDate.map(item => {
        return item.name
      })
      const dataOption = {
        yAxis: {
          data: yAxisArr
        },
        series: {
          data: xAxisArr
        },
      }
      this.echartsInstance.setOption(dataOption)
    },
    startIntever() {
      if (this.timeid) {
        clearInterval(this.timeid)
      }
      this.timeid = setInterval(() => {
        this.currentPage++
        if (this.currentPage > this.totalPage) {
          this.currentPage = 1
        }
        this.updataEchart()
      }, 3000)
    },
    updataScreen() {
      const titleFontsize = this.$refs.seller_ref.offsetWidth / 100 * 3.6
      const upscreenOption = {
        title: {
          textStyle: {
            fontSize: titleFontsize
          },
        },
        tooltip: {
          axisPointer: {
            lineStyle: {
              width: titleFontsize,
            }
          }
        },
        series: [
          {
            barWidth: titleFontsize,
            barBorderRadius: [0, titleFontsize / 2, titleFontsize / 2, 0]
          }
        ]
      }
      this.echartsInstance.setOption(upscreenOption)
      this.echartsInstance.resize()
    }
  }
}

5.完整项目

205

6.总结

举报

相关推荐

0 条评论