天天看點

Vue系列——在vue項目中使用echarts

該示例使用 vue-cli 腳手架搭建

安裝echarts依賴

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 
           

Hello.vue

<div id="myChart" :style="{width: '300px', height: '300px'}"></div>
           
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
    this.drawLine();
  },
  methods: {
    drawLine(){
        // 基于準備好的dom,初始化echarts執行個體
        let myChart = this.$echarts.init(document.getElementById('myChart'))
        // 繪制圖表
        myChart.setOption({
            title: { text: '在Vue中使用echarts' },
            tooltip: {},
            xAxis: {
                data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]
            },
            yAxis: {},
            series: [{
                name: '銷量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        });
    }
  }
}
           

注意: 這裡echarts初始化應在鈎子函數mounted()中,這個鈎子函數是在el 被新建立的 vm.$el 替換,并挂載到執行個體上去之後調用

按需引入

上面全局引入會将所有的echarts圖表打包,導緻體積過大,是以我覺得最好還是按需引入。

Hello.vue

// 引入基本模闆

let echarts = require('echarts/lib/echarts')

// 引入柱狀圖元件

require('echarts/lib/chart/bar')

// 引入提示框和title元件

require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
export default {
  name: 'hello',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted() {
    this.drawLine();
  },
  methods: {
    drawLine() {
      // 基于準備好的dom,初始化echarts執行個體
      let myChart = echarts.init(document.getElementById('myChart'))
      // 繪制圖表
      myChart.setOption({
        title: { text: 'ECharts 入門示例' },
        tooltip: {},
        xAxis: {
          data: ["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]
        },
        yAxis: {},
        series: [{
          name: '銷量',
          type: 'bar',
          data: [5, 20, 36, 10, 10, 20]
        }]
      });
    }
  }
}
           

這裡之是以使用 require 而不是 import,是因為 require 可以直接從 node_modules 中查找,而 import 必須把路徑寫全。

頁面展示

參考文章

使用 Echarts 建立圖表

Vue 2.x 實戰之背景管理系統開發

echarts圖表自适應問題

--------------------- 

作者:ChosenWu 

來源:CSDN 

原文:https://blog.csdn.net/mr_wuch/article/details/70225364 

版權聲明:本文為部落客原創文章,轉載請附上博文連結!

繼續閱讀