vue中echarts的使用
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>