vue項目中引用echarts的幾種方式


准備工作:

首先我們初始化一個vue項目,執行vue init webpack echart,接着我們進入初始化的項目下。安裝echarts,

  1. npm install echarts -S //或
  2.  cnpm install echarts -S

安裝完成之后,我們就可以開始引入我們需要的echarts了,接下來介紹幾種使用echarts的方式。

全局引用:

首先在main.js中引入echarts,將其綁定到vue原型上:

  1.   import echarts from 'echarts'
  2. Vue.prototype.$echarts = echarts;

接着,我們就可以在任何一個組件中使用echarts了,接下來我們在初始化項目中的helloWorld組件中使用echarts配置圖標,具體如下:

<template>
    <div>
         <div style="width:500px;height:500px" ref="chart"></div>
    </div>
</template>
<script>
export default{
   data () {
  return {};
 },
 methods: {
  initCharts () {
  let myChart = this.$echarts.init(this.$refs.chart);
  console.log(this.$refs.chart)
  // 繪制圖表
  myChart.setOption({
  title: { text: '在Vue中使用echarts' },
  tooltip: {},
  xAxis: {
  data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]
  },
  yAxis: {},
  series: [{
  name: '銷量',
  type: 'bar',
  data: [5, 20, 36, 10, 10, 20]
  }]
  });
  }
   },
   mounted () {
  this.initCharts();
 }
}
</script>

這樣下來,就可以在項目的任何地方使用echarts了。

局部使用:

當然,很多時候沒必要在全局引入ecahrts,那么我們只在單個組件內使用即可,代碼更加簡單:

<template>
<div>
<div style="width:500px;height:500px" ref="chart"></div>
</div>
</template>
<script>
const echarts = require('echarts');
export default{
data () {
return {};
},
methods: {
initCharts () {
let myChart = echarts.init(this.$refs.chart);
// 繪制圖表
myChart.setOption({
title: { text: '在Vue中使用echarts' },
tooltip: {},
xAxis: {
data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]
},
yAxis: {},
series: [{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
}
},
mounted () {
this.initCharts();
}
}
</script>

可以看到,我們直接在組件內引入echarts,接下來跟全局引入的使用一樣。區別在於,這種方式如果你想在其他組件內用echarts,則必須重新引入了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM