在vue-cli項目中使用echarts

這個示例使用 vue-cli 腳手架搭建html

安裝echarts依賴

npm install echarts -S

或者使用國內的淘寶鏡像:vue

  • 安裝
    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 替換,並掛載到實例上去以後調用node

    按需引入

    上面全局引入會將全部的echarts圖表打包,致使體積過大,因此我以爲最好仍是按需引入。git

  • 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 必須把路徑寫全。github

  • 頁面展現vue-cli

  •  

 若是須要引入像字符雲之類的官方包裏沒有的圖表,能夠在github上找到,如何使用具體請參考我前一陣子的文章http://www.cnblogs.com/Smiled/p/7146550.htmlnpm

字符雲示例:echarts

cnpm install echarts -S

在須要使用的頁面引入dom

 require('echarts-wordcloud');

頁面展現:函數

相關文章
相關標籤/搜索