一、首先安裝 eCharts 依賴
npm install echarts -S
二、main.js 引入 eCharts 依賴
2.1)在 main.js 中引入
import echarts from 'echarts' Vue.prototype.$echarts = echarts
2.2)HTML.vue
export default { name: 'hello', data () { return { msg: 'Welcome' } }, 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 替換,並掛載到實例上去之后調用
三、新建獨立 js 文件引入 eCharts
3.1)新建 myCharts.js 用於封裝各種 eCharts
/** * 各種畫echarts圖表的方法都封裝在這里 */ //導入eCharts import echarts from 'echarts' const myCharts= function (Vue) { Object.defineProperties(Vue.prototype, { $chart: { get() { return { line: function (id) { this.chart = echarts.init(document.getElementById(id)); this.chart.clear(); const optionData = { title: { text: '某站點用戶訪問來源', subtext: '純屬虛構', x: 'left' }, tooltip: { trigger: 'axis' }, legend: { data: ['郵件營銷', '聯盟廣告', '視頻廣告', '直接訪問', '搜索引擎'] }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, lineStyle: { }, xAxis: { type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [{ name: '郵件營銷', type: 'line', stack: '總量', data: [120, 132, 101, 134, 90, 230, 210] }, { name: '聯盟廣告', type: 'line', stack: '總量', data: [220, 182, 191, 234, 290, 330, 310] }, { name: '視頻廣告', type: 'line', stack: '總量', data: [150, 232, 201, 154, 190, 330, 410] }, { name: '直接訪問', type: 'line', stack: '總量', data: [320, 332, 301, 334, 390, 330, 320] }, { name: '搜索引擎', type: 'line', stack: '總量', data: [820, 932, 901, 934, 1290, 1330, 1320] } ] }; this.chart.setOption(optionData); } } } } }) } export default { myCharts }
3.2)在 main.js 中引用
//引入eCharts import myCharts from './views/charts/mycharts.js' //路徑看自己情況而定 Vue.use(myCharts) //引入eCharts
3.3)在頁面中使用
<template> <div id="chart"> <div id="chart-line"></div> </div> </template> <script> export default { data() { return {}; }, mounted() { this.$chart.line("chart-line"); } }; </script> <style scoped> #chart{ text-align: left; } #chart-line,#chart-bar,#chart-pie { width: 100%; height: 300px; } </style>
四、使用 vue-echarts
這個沒用過,聽說能省不少事,就是不知道能不能支持所有的圖表,以后有機會試一試