vue使用echarts
cnpm install echarts -S
import echarts form 'echarts'
Vue.prototype.$echarts=echarts
<template>
<div ref="chart" style="width:100%;height:225px"></div>
</template>
<script>
export default {
data() {
return {
option: {}
}
},
created() {
this.getData()
},
mounted(){
this.getEchartData()
},
methods: {
getData() {
},
getEchartData() {
let that = this
const chart = that.$refs.chart
if (chart) {
const myChart = this.$echarts.init(chart)
myChart.setOption(that.option)
window.addEventListener("resize", function() {
myChart.resize()
})
}
this.$on('hook:destroyed',()=>{
window.removeEventListener("resize", function() {
myChart.resize();
});
})
},
}
</script>
发现报错,this上没有$echarts , 原因:echarts版本太高。
npm install echarts@4.8.0 --save
let echarts = require('echarts')
但页面什么都没有显示,也没有报错(解决办法)
- 添加watch方法监听option数据的变化重新设置数据
watch: {
option: {
handler(newVal, oldVal) {
if (this.myChart) {
if (newVal) {
this.myChart.setOption(newVal);
} else {
this.myChart.setOption(oldVal);
}
} else {
this.getEchartData();
}
},
deep: true
}
}