在vue中使用echarts有兩種方法
一、第一種方法
1、通過npm獲取echarts
npm install echarts --save
2、在vue項目中引入echarts
在 main.js 中添加下面兩行代碼
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
注:import echarts from 'echarts' 引入echarts后,不能全局使用echarts,所以通過Vue.prototype將echarts保存為全局變量。原則上$echarts可以為任意變量名。
3、新建Echarts.vue文件
在 template 中添加一個存放echarts的‘div’容器
添加 myEcharts() 方法,將官方文檔中的script內容復制到myEcharts()中
修改 echarts.init() 為 this.$echarts.init() ,因為上面第二部,將echarts保存到全局變量$echarts中。
在mounted中調用myEcharts()方法
//在Echarts.vue文件中 <template> <div class="Echarts"> <div id="main" style="width: 600px;height: 400px;"></div> </div> </template> <script> export default { name: 'Echarts', methods: { myEcharts(){ var myChart = this.$echarts.init(document.getElementById('main')); //配置圖表 var option = { title: { text: 'echarts入門示例', }, tooltip: {}, legend: { data: ['銷量'] }, xAxis: { data: ['襯衫','羊毛衫','雪紡衫','褲子','高跟鞋','襪子'] }, yAxis: {}, series: [{ name: '銷量', type: 'bar', data: [5,20,36,10,10,20] }] }; myChart.setOption(option); } }, mounted(){ this.myEcharts(); } } </script> <style> </style>
注:本例函數中使用ES6寫法。mounted(){}等同於mounted:function(){}。myEcharts()方法同理。最后添加進行路由配置。
二、使用vue-echarts
1、先npm安裝vue-echarts
npm install echarts vue-echarts
2、除了全量引用echarts,我們還可以采用按需引入的方式
//在main.js中引入 import Echarts from 'vue-echarts' import 'echarts/lib/chart/line' Vue.component('chart',Echarts)
3、然后在組件中使用
//hello.vue中 <template> <div class="hello"> <chart ref="chart1" :options="orgOptions" :auto-resize="true"></chart> </div> </template> <script> export default { name: 'hello', data() { return { orgOptions: {}, } }, mounted() { this.orgOptions = { xAxis: { type: 'category', data: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] }, yAxis: { type: 'value' }, series: [{ data: [820,932,901,934,1290,1330,1320], type: 'line', smooth: true }] } } } </script> <style> </style>
