本文歸柯三(kesan)全部,轉載請註明出處 http://www.javashuo.com/article/p-elgbhctr-ck.htmlvue
系統中已經安裝以下組件node
npm install echarts
在組件源碼處引入echarts組件webpack
import echarts from 'echarts'
若是須要按需引入,請參考官方文檔
點此查看官方文檔web
先定義一個寬高均爲500px的div以供echarts繪出組件vue-cli
<template> <div> <div id="test" style="width:500px;height:500px"> </div> </div> </template>
定義組件須要的屬性
在本例中,咱們定義了兩個須要由用戶來提供數據的屬性npm
props: { 'xData': Array, 'yData': Array }
初始化柱形圖組件echarts
首先咱們須要定義柱形圖的option (title也能夠抽出來設置爲屬性)函數
option: { title: { text: 'Vue柱形圖組件' }, xAxis: { type: 'category', data: [] }, yAxis: { type: 'value' }, series: [ { name: '銷量', type: 'bar', data: [] } ] }
** 初始化組件 **this
this.chart = echarts.init(document.getElementById("test")) this.option.xAxis.data = this.xData this.option.series[0].data = this.yData this.chart.setOption(this.option)
首先來看一看著名的Vue生命週期圖:
很顯然在Created時組件都還沒渲染,所以比較合適的時機是在mounted完成以後執行ECharts組件初始化的操做。
也就是說咱們要將ECharts初始化工做放到mounted函數中執行,若是放入到Created中就會出錯,由於Created時組件還未進行渲染工做。
<template> <div> <div id="test" style="width:500px;height:500px"> </div> </div> </template> <script> /* eslint-disable */ import echarts from 'echarts' export default { name: 'Histogram', data: function () { return { option: { title: { text: 'Vue柱形圖組件' }, xAxis: { type: 'category', data: [] }, yAxis: { type: 'value' }, series: [ { name: '銷量', type: 'bar', data: [] } ] }, chart: {} } }, props: { 'xData': Array, 'yData': Array }, methods: { updateData: function () { console.log("update data") } }, created: function (){ console.log(this.xData) console.log('created') }, mounted: function(){ this.chart = echarts.init(document.getElementById("test")) this.option.xAxis.data = this.xData this.option.series[0].data = this.yData this.chart.setOption(this.option) } } </script>
Vue.component('組件名', 組件)