1. 程式人生 > 其它 >在vue-cli專案中使用echarts

在vue-cli專案中使用echarts

引入echarts

cnpm install echarts -S
  • 全域性引入

  • main.js

    // 引入echarts
    import echarts from 'echarts'
    
    Vue.prototype.$echarts = echarts 

    index.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圖表打包,導致體積過大,所以我覺得最好還是按需引入。

   index.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 {
  ……  
}

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