1.安裝 echarts 依賴
npm install echarts --save
2.main.js 中引入 echarts 依賴
import echarts from 'echarts'
Vue.prototype.$echarts = echarts;
3.封裝 echarts 的組件
在一個項目中我們通常會多次用到圖表,這里建議先封裝成組件再應用;
新建chart.vue文件
<template> <div class="chart" :id="id"></div> </template> <script> export default{ props: ['parOption', 'id', 'domWidth'], data () { return { chart: '' } }, created () { }, mounted () { this.init() }, components: { }, methods: { init () { this.chart = this.$echarts.init(document.getElementById(this.id)) this.chart.setOption(this.parOption) } }, watch: { parOption: { handler (val, oldVal) { if (this.chart) { this.chart.setOption(val) } }, deep: true }, domWidth (val, oldVal) {
// 刷新圖表 this.chart.resize() } } } </script> <style lang="less" scoped> .chart{ width: 100%; height: 100%; } </style>
4.在頁面中引用chart組件
<template> <div class="echarts"> <h2>Echarts 圖表</h2> <Chart :parOption="option" id="chart1" :domWidth="domWidth"></Chart> <Chart :parOption="option" id="chart2" :domWidth="domWidth"></Chart> <Chart :parOption="option" id="chart3" :domWidth="domWidth"></Chart> </div> </template> <script> // 引入chart import Chart from '@/components/chart' export default{ data () { return { tab: '0', option: { tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)' }, series: [ { name: '工時統計', type: 'pie', radius: ['45%', '65%'], itemStyle: { normal: { label: { show: true, formatter: '{b} : {c}' }, labelLine: {show: true} } }, label: { normal: { show: true, position: 'outside', // position: 'inside', textStyle: { fontSize: '14', fontWeight: 'bold' }, formatter: '{b}\n{d}%' }, emphasis: { show: true, textStyle: { fontSize: '14', fontWeight: 'bold' } } }, labelLine: { normal: { show: true, length: 15, length2: 10, lineStyle: {} } }, data: [] } ], color: ['#b7dd73', '#ffdb8a'] }, domWidth: document.documentElement.clientWidth } }, created () { }, mounted () { // 獲取瀏覽器窗口寬度 window.onresize = () => { const domWidth = document.documentElement.clientWidth this.domWidth = domWidth } }, methods: { }, components: { Chart } } </script> <style lang="less" scoped> .echarts{ width: 60%; margin: 0 auto; } </style>