vue使用v-chart的实践心得
开发Vue2和Vue3时,我们常常需要将数据以图表的形式展示给用户,而 V-Chart 作为一个轻量级且易于集成的图表库,是 Vue 开发的首选。这篇文章,我将写一下关于我在使用这方面的心得。
echarts官网:https://echarts.apache.org/examples/zh/index.html
v-chart:https://github.com/ecomfe/vue-echarts
-------------------------------------------------------- 后续,我会持续补充内容进来
安装与配置(vue3举例)
npm install vue-echarts echarts --save
安装完成后,在需要使用图表的组件中引入并注册 V-Chart 组件:效果实例
<script lang="ts" setup name="lineCharts">
const chartsLineOptionQPS = ref({
title: {
text: '折线图'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
legend: {
data: ['Email', 'Union Ads', 'Video Ads', 'Direct']
},
toolbox: {
feature: {
saveAsImage: {}
}
},
grid: {
left: '35px',
right: '35px',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Email',
type: 'line',
stack: 'Total',
areaStyle: {},
emphasis: {
focus: 'series'
},
data: [120, 132, 101, 134, 90, 230, 210],
},
{
name: 'Union Ads',
type: 'line',
stack: 'Total',
areaStyle: {},
emphasis: {
focus: 'series'
},
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: 'Video Ads',
type: 'line',
stack: 'Total',
areaStyle: {},
emphasis: {
focus: 'series'
},
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: 'Direct',
type: 'line',
stack: 'Total',
areaStyle: {},
emphasis: {
focus: 'series'
},
data: [320, 332, 301, 334, 390, 330, 320]
}
]
})
</script>
在模板中使用 v-chart 组件来渲染图表:
<template>
<v-chart :options="chartData"></v-chart>
</template>
使用技巧与实践
使用v-chart很方便使用,具体的图表配置如折线、饼图等,直接copy官网charts的配置数据就可以。但是也有些特殊的情况需要处理,如下:(后续,我会持续补充内容进来)
1、v-chart随屏幕自动调整图表大小:autoresize
echarts图表设置自适应,使用这个参数,我们就不需要自己监听屏幕resize变化了。
<v-chart :option="option" autoresize />
2、v-chart动态数据及时响应:notMerge:true
vue如何使用v-chart组件,没有及时更新数据。
<v-chart :option="option" autoresize :update-options="{notMerge:true}"/>
其他详见:https://github.com/ecomfe/vue-echarts