要在 Element UI 中引入 ECharts,首先需要安装 ECharts 和 Element UI。
在项目引入echart:
npm install echarts --save
然后封装一个Echarts.vue组件(resize-detector这是监听dom的,建议安装哈):
<template> <div ref="chartDom"></div> </template> <script> import * as echarts from 'echarts' import debounce from 'lodash/debounce' import { addListener, removeListener } from 'resize-detector' export default { props: { option: { type: Object, default: () => { } } }, watch: { // option(val) { // this.chart.setOption(val); // }, option: { handler(val) { this.chart.setOption(val) }, deep: true } }, created() { this.resize = debounce(this.resize, 300) }, mounted() { this.renderChart() addListener(this.$refs.chartDom, this.resize) }, beforeDestroy() { removeListener(this.$refs.chartDom, this.resize) this.chart.dispose() this.chart = null }, methods: { resize() { this.chart.resize() }, renderChart() { this.chart = echarts.init(this.$refs.chartDom) this.chart.setOption(this.option) } } } </script> <style> </style>
然后在需要的页面引入调用(必须要给echarts组件设置一个高度哦,不然不显示的):
<template> <div class="app-container"> <echarts class="echart-item" :option="option" ref="chartDom"></echarts> <echarts class="echart-item" :option="option1" ref="chartDom"></echarts> </div> </template> <script> import Echarts from '@/components/echart/Echarts.vue' export default { name: 'Dashboard', components: { Echarts }, computed: { }, data() { return { option: { title: { text: 'Referer of a Website', subtext: 'Fake Data', left: 'center' }, tooltip: { trigger: 'item' }, legend: { orient: 'vertical', left: 'left' }, series: [ { name: 'Access From', type: 'pie', radius: '50%', data: [ { value: 1048, name: 'Search Engine' }, { value: 735, name: 'Direct' }, { value: 580, name: 'Email' }, { value: 484, name: 'Union Ads' }, { value: 300, name: 'Video Ads' } ], emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }, option1: { 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 } ] }, list: [] } }, created() { // this.get_data() }, methods: { get_data() { api.getList().then(res => { this.list = res.data }) } } } </script> <style scoped> .app-container { margin-top: 20px; } .echart-item{ height: 300px; } </style>
效果:
扩展:echart 示例网站
https://echarts.apache.org/examples/zh/index.html#chart-type-line