天天看點

vue項目中使用echarts

1、安裝

npm install echarts --save
           

下方是我微信公衆号的二維碼,可以掃碼關注以下,後期博文推送主要在公衆号上面,有什麼問題也可以通過公衆号跟我發消息哦~

vue項目中使用echarts

2、使用

在需要用到的頁面引入

以下分别舉例餅圖、折線圖、柱狀圖

一、例1(餅圖):

vue項目中使用echarts
<!-- 圖表 -->
 <template>
 
    <div>
      <div style="height:400px;" ref="chart"></div>
    </div>
    
</template>

<script>
import echarts from 'echarts'
export default {
  mounted() {
    this.chartInit()
  },
  methods: {
    chartInit() {
      const myChart = echarts.init(this.$refs.chart);
      const colors = ['#6CCCEB', '#FF8F4B', '#FFEF83', '#6FE59C'];   // 定義餅塊的顔色系列
      let option = {
        title: {
          text:  'xxx統計圖',  // 标題
          left: 'center'      // 設定标題居中
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 80,     // 離右側的距離(備注的餅圖餅塊的名稱離右側的距離 如上圖右側展示)
          top: 20,       // 離上方的距離
          data: ['3000元以下', '3000-4000元', '4000-5000元', '5000元以上']
        },
        series: [
          {
            name: '薪資',   //  滑鼠放在每個餅塊上顯示的餅塊類别
            type: 'pie',   
            radius: '55%',
            center: ['50%', '50%'],    // 餅圖位置
            data: [
              {
                value: 20,     // 用來算餅塊占比
                name: '3000元以下',
                itemStyle: {    // 餅塊的顔色
                  color: colors[0]
                },
              },
              {
                value: 30, name: '3000-4000元',
                itemStyle: {
                  color: colors[1]
                },
              },
              {
                value: 20,
                name: '4000-5000元',
                itemStyle: {
                  color: colors[2]
                },              
              },
              {
                value: 30,
                name: '5000元以上',
                itemStyle: {
                  color: colors[3]
                },              
              },
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',   // 滑鼠放在餅塊時的陰影
              }
            },
          }
        ]
      };
      myChart.setOption(option);

    },
  }
}
</script>

           

一、例2(柱狀圖):

vue項目中使用echarts
<template>
    <!-- 柱狀圖 -->
    <div>
      <div style="height:400px;" ref="chart"></div>
    </div>
</template>

<script>
import echarts from 'echarts'
export default {
  mounted() {
    this.chartInit()
  },
  methods: {
    chartInit() {
      const myChart = echarts.init(this.$refs.chart);
      let option = {
        title: {
          text: 'xxx統計',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['浏覽數', '申請數'],
          right: 120,
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六'],
          }
        ],
        yAxis: [
          {
            type: 'value',
            splitLine: {
              show: false  // 去掉y軸預設的橫線
            }
          }
        ],
        series: [
          {
            name: '浏覽數',
            type: 'bar',
            barWidth: 20,  // 柱狀圖 寬度20px
            data: [8, 5, 0, 3, 1, 7],
            label: {  //标記數量
              normal: {
                show: true,
                position: 'top'
              }
            },
            itemStyle: {   //  設定柱狀圖顔色
              color: '#FF624A'
            },
          },
          {
            name: '申請數',
            type: 'bar',
            barWidth: 20, // 柱狀圖 寬度
            data: [5, 1, 6, 4, 0, 2],
            label: {  //标記數量
              normal: {
                show: true,
                position: 'top'
              }
            },
            itemStyle: {
              color: '#6FE59B'
            },
          }
        ]
      };
      myChart.setOption(option);

    },

  }
}
</script>
           

一、例2(折線圖):

vue項目中使用echarts
<template>
    <!-- 折線圖 -->
    <div>
      <div style="height:400px;" ref="chart"></div>
    </div>
</template>

<script>
import echarts from 'echarts'
export default {
  mounted() {
    this.chartInit()
  },
  methods: {
    chartInit() {
      const myChart = echarts.init(this.$refs.chart);
      let option = {
        title: {  //标題
          text: 'xxx報表',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: ['第1周', '第2周', '第3周', '第4周'],

        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false  // 去掉y軸預設的橫線
          }
        },
        series: [
          {
            data: [0, 30, 23, 41],
            type: 'line',
            smooth: true,    // 是否是平滑線條
            itemStyle: {
              borderWidth: 2,       // // 折線與x軸虛線相交處的小點顔色線大小
              borderColor: '#fe472b',    // 折線與x軸虛線相交處的小點顔色
              color: '#fe472b'    // 折線顔色
            },
            label: {  //标記數量
              normal: {
                show: true,
                position: 'top'
              }
            },
            markLine: { // x軸虛線
              symbol: ['none', 'none'],
              label: { show: false },
              lineStyle: {   // 虛線顔色
                color: '#ccc',
              },
              data: [
                { xAxis: 0 },  // x軸虛線位置
                { xAxis: 1 },
                { xAxis: 2 },
                { xAxis: 3 }
              ]
            },
          }
        ]
      };
      myChart.setOption(option);

    },
   
    }
  }
}
</script>


           

**

實際應用:echarts 資料通過調接口擷取

**

vue項目中使用echarts
<template>
  <div class="page">
    <p>{{eName}}統計資料</p>
    <div class="search">
      <ul class="search-list">
        <li :class="{'white': true, 'active': isActive==index, 'white-color':isActive==index }" v-for="(item,index) in searchList" :key="index" @click="handleClick(item,index)">{{item.title}}</li>
      </ul>
      <el-button type="primary" size="small"  @click="handleExport">下載下傳</el-button>
    </div>

    <!-- 圖表 -->
    <div class="charts" v-if="!show">
      <div style="height:400px;" ref="chart"></div>
    </div>
    <!-- 統計表格 -->
    <div class="data">
      <el-table :data="tableData" style="width: 100%"  id="exportTable">
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="keyName" :label="this.title" align="center"></el-table-column>
        <el-table-column prop="value" label="總數" align="center"></el-table-column>
        <el-table-column prop="result" label="百分比" align="center"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'  // 圖表
import { countOfApplyResumeGroupBy } from '@/apis/apis'
import FileSaver from 'file-saver'  // 下載下傳表格資料
import XLSX from 'xlsx'  // 下載下傳表格資料
export default {
  data() {
    return {
      isActive: 0, 
      searchList: [
        { title: "性别", tag: "sex" },
        { title: "年齡", tag: "age" },
        { title: "學曆", tag: "edu" },
        { title: "工作經驗", tag: "work_age" },
      ],
      title: '性别',
      groupType: '',        // title(性别) 對應的英文(傳給背景)
      pieData: [],          //餅圖資料
      menuList: [],         // 餅圖右上方标注
      colors: ['#6CCCEB', '#FFEF83', '#6FE59C', '#FF8F4B', '#FDBC3C', '#B9C5DD', '#6089D9', '#30BEEC'],   // 餅圖每塊的顔色
      show: false,   //是否顯示圖表
      tableData: [],  // 統計表格資料
      id: '',
      eName: '',
    }
  },
  created() {
    this.id = this.$route.query.id;
    this.eName= this.$route.query.name;
    this.getList();
  },
  methods: {
    //擷取餅圖資料
    getList() {
      let params = {
        id: this.id,
        groupType: this.groupType || 'sex'  // 剛開始傳sex,和title對應
      }
      countOfApplyResumeGroupBy({ data: params }).then(res => {
        if (res.code == 0) {
          this.pieData = [];   //  清空餅圖資料
          if (res.data.length == 0) {   // 如果沒有資料,餅圖部分隐藏
            this.show = true
            return;
          }
          this.menuList = res.data.map(element => element.keyName);  //餅圖上方右側标注
          res.data.forEach((element, index) => {
            this.tableData = res.data;
            this.pieData.push({
              value: element.value,
              name: element.keyName,
              itemStyle: { color: this.colors[index] }
            })
          });
          this.chartInit()    // 渲染餅圖
        }
      })
    },
    //餅圖
    chartInit() {
      const myChart = echarts.init(this.$refs.chart);
      let option = {
        title: {
          text: this.title + '統計圖',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 80,
          top: 20,
          // data: ['3000元以下', '3000-4000元', '4000-5000元', '5000元以上'],
          data: this.menuList,
        },
        series: [
          {
            name: this.title,
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            // data: [
            //   {
            //     value: 20,
            //     name: '3000元以下',
            //     itemStyle: {  color: colors[0]  // 餅塊的顔色 },
            //   },
            // ],
            data: this.pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              }
            },
          }
        ]
      };
      myChart.setOption(option);
    },
    //點選切換類目: 性别、年齡等
    handleClick(item, index) {
      this.isActive = index;
      this.title = item.title;
      this.groupType = item.tag;
      this.getList();  // 擷取資料,渲染餅圖
    },

    //下載下傳
    handleExport() {
      this.$confirm('該操作将導出統計資料,是否繼續?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let exportTable = XLSX.utils.table_to_book(document.querySelector('#exportTable'))
        let exportTableOut = XLSX.write(exportTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([exportTableOut], { type: 'application/octet-stream' }), `${this.title}統計.xlsx`)
        } catch (e) { if (typeof console !== 'undefined') console.log(e, exportTableOut) }
        return exportTableOut;
      }).catch(() => { });
    },
  }
}
</script>

<style lang="less" scoped>
.page {
  .search {
    color: #333;
    .search-list {
      li {
        width: 100px;
        line-height: 34px;
        text-align: center;
        font-size: 14px;
        display: inline-block;
        margin-right: 20px;
      }
      .active {
        background-color: #ff6750;
      }
    }
  }
  .data {
    padding: 20px 40px 50px 40px;
  }
}
</style>
           

繼續閱讀