在vue腳手架里如何使用echarts

<h2>第一步:肯定是把插件引入進(jìn)去</h2>

npm install echarts -S

如果上面的引入報(bào)錯(cuò),可以使用淘寶鏡像

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

<h2>第二步 : 可以全局引入,或者是按需引入</h2>

<h3>全局引入</h3>
<h4>在main.js里</h4>

// 引入echarts
import echarts from 'echarts'
//一般都要加個(gè)$加到vue的原型鏈上,方便引用
Vue.prototype.$echarts = echarts 

<h4>新建一個(gè)chart.vue組件</h4>

<template>
 <div>
     <div id="chart" class="chart">

     </div>
 </div>
</template>

<script>
  export default {
      data(){
          return{}
      },
      mounted(){
          this.myChart = 
              this.$echarts.init(document.getElementById("chart"));
          this.drawChart();
      },
      methods:{
          drawChart(){
             let option = {
                  xAxis: {
                      type: 'category',
                      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                  },
                  yAxis: {
                      type: 'value'
                  },
                  series: [{
                      data: [120, 200, 150, 80, 70, 110, 130],
                      type: 'bar'
                  }]
              };

             this.myChart.setOption(option);
                window.onresize = function(){
                       this.myChart.resize()
                  }
         
          }
      }
  }
</script>

上面是個(gè)柱狀圖的demo,缺點(diǎn):全局引入會(huì)將所有的echarts圖表打包,導(dǎo)致體積過大,如果echarts圖用的比較少,可以考慮按需引入

<h3>按需引入</h3>

<script>
// 引入基本模板
let echarts = require('echarts/lib/echarts')
// 引入柱狀圖組件
require('echarts/lib/chart/bar')
// 引入提示框和title組件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
//引入右上角下載圖片等等一系列的toolbox的功能
require('echarts/lib/component/title/toolbox')
  export default {
  //里面代碼同上
}
</script>

這里之所以使用 require 而不是 import,是因?yàn)?require 可以直接從 node_modules 中查找,而 import 必須把路徑寫全。

圖表適應(yīng)屏幕

  $(window).resize(function() {
          chart.resize()
        })
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容