安装vue
yarn add vue
yarn add --dev @types/vue
在vue-index.html中准备Echarts显示区域root
<body>
<div id="root"></div>
<script src="vue-main.js"></script>
</body>
在vue-main.js中渲染vue,挂载到root上
new Vue({
render: h=>h(VueApp)
}).$mount(document.getElementById('root'))
在vue-app.vue里初始化echarts数据
<template>
<div>
<vue-echarts :option="option" :loading="loading"></vue-echarts>
<button @click="loadMore">加载更多</button> //点击更新数据
</div>
</template>
<script lang="ts">
import VueEcharts from './vue-echarts.vue';
export default {
data() { //初始化echarts数据
return {
loading: false,
option: {
title: {
show: true,
text: '销量',
right: 20,
},
legend: {
data: [`金额`]
},
tooltip: {
show: true
},
xAxis: {
type: 'category',
data: ['2020-1-1', '2020-1-2', '2020-1-3']
},
yAxis: {
type: 'value'
},
series: [{
lineStyle: {
color: 'blue'
},
itemStyle: {
borderWidth: 10
},
name: '金钱',
data: [11, 22, 8],
type: 'line'
}]
}
};
},
components: {VueEcharts},
methods: {
loadMore() { //添加数据,更新echarts
this.loading = true;
setTimeout(() => {
this.loading = false;
this.option = {
xAxis: {
data: ['2020-1-1', '2020-1-2', '2020-1-3', '2020-1-4', '2020-1-5']
},
series: [{
data: [11, 22, 8, 7, 12],
}]
};
}, 1500);
}
}
};
</script>
封装echarts组件:vue-echarts.vue
<template>
<div ref="container">
</div>
</template>
<script>
import echarts from 'echarts'
export default {
props: ['option', 'loading'], //接收外部传入的option, loading
mounted() { //第一次渲染,挂载之后拿到div(container)
const width = document.documentElement.clientWidth
this.$refs.container.style.with = `${width - 20}px` //设置div的宽高
this.$refs.container.style.height = `${(width - 20) * 1.2}px`
this.chart = echarts.init(this.$refs.container) //初始化div
this.chart.setOption(this.option) //初始化图表
},
watch: { //监听option的变化,数据变化后更新echarts
option() {
this.chart.setOption(this.option)
},
loading() { //监听加载动画
if (this.loading) {
this.chart.showLoading()
} else {
this.chart.hideLoading()
}
}
}
};
</script>