如何在 Vue 項目中使用 echarts

數據的重要性我們大家都知道,就算再小的項目中都可能使用幾個圖表展示,我最近在做項目的過程中也是需要用到圖表,最後選擇了echarts 圖表庫,爲什麼選擇 echarts,第一:簡單上手容易,第二:它幾乎可以滿足我們所有的開發需要,第三:echarts 應該是國內做的最好的可視化庫之一了。

廢話不多說,那我們就看看如何在 Vue 的項目中使用 echarts。

第一種方法,直接引入echarts

安裝echarts項目依賴
npm install echarts --save

//或者
npm install echarts -S

如果沒有科學上網的朋友可以使用國內的淘寶鏡像。

npm install -g cnpm --registry=https://registry.npm.taobao.org

cnpm install echarts -S
全局引入

我們安裝完成之後,可以在 main.js 中全局引入 echarts

import echarts from "echarts";
Vue.prototype.$echarts = echarts;
創建圖表
<template>
  <div id="app">
    <div id="main" style="width: 600px;height:400px;"></div>
  </div>
</template>
export default {
  name: "app",
  methods: {
    drawChart() {
      // 基於準備好的dom,初始化echarts實例
      let myChart = this.$echarts.init(document.getElementById("main"));
      // 指定圖表的配置項和數據
      let option = {
        title: {
          text: "ECharts 入門示例"
        },
        tooltip: {},
        legend: {
          data: ["銷量"]
        },
        xAxis: {
          data: ["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]
        },
        yAxis: {},
        series: [
          {
            name: "銷量",
            type: "bar",
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      };
      // 使用剛指定的配置項和數據顯示圖表。
      myChart.setOption(option);
    }
  },
  mounted() {
    this.drawChart();
  }
};
</script>

第二種方法,使用 Vue-ECharts 組件

安裝組件
npm install vue-echarts -S
使用組件
<template>
  <div id="app">
    <v-chart class="my-chart" :options="bar"/>
  </div>
</template>
<script>
import ECharts from "vue-echarts/components/ECharts";
import "echarts/lib/chart/bar";
export default {
  name: "App",
  components: {
    "v-chart": ECharts
  },
  data: function() {
    return {
      bar: {
        title: {
          text: "ECharts 入門示例"
        },
        tooltip: {},
        legend: {
          data: ["銷量"]
        },
        xAxis: {
          data: ["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]
        },
        yAxis: {},
        series: [
          {
            name: "銷量",
            type: "bar",
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      }
    };
  }
};
</script>
<style>
.my-chart {
  width: 800px;
  height: 500px;
}
</style>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章