最近有個需求頁面,有不少echart圖表一個一個寫太麻煩,本身琢磨+借鑑大佬的代碼封裝了一個web
<template> <div :id=id :data=data></div> </template> <script> export default { props: ['id', 'data'], data () { return { ChartLineGraph: null } }, watch: { data: { handler (newValue, oldValue) { this.drawLineGraph(this.id, newValue) }, deep: true } }, mounted () { this.drawLineGraph(this.id, this.data) }, methods: { drawLineGraph (id, data) { // eslint-disable-next-line no-unused-vars let _this = this let muChart = document.getElementById(id) this.ChartLineGraph = this.$echarts.init(muChart) this.ChartLineGraph.setOption(data) window.addEventListener('resize', function () { _this.ChartLineGraph.resize() }) } }, beforeDestroy () { if (this.ChartLineGraph) { this.ChartLineGraph.clear() } }, components: { } } </script> <style scoped> </style>
import linegraph from '../components/methods' data () { return{ // 這裏就是你傳的echart數據 option: { 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' }], tooltip: {} } } } components: { linegraph }
<linegraph :id="'ss'" :data='option' style="width:500px;height:300px"</linegraph>