Vue3 setup组合式语法优雅地使用Echarts库

Vue3 setup组合式语法优雅地使用Echarts库

1. 安装Echarts

npm或者yarn安装

npm install echarts
yarn add echarts

2.main.js全局挂载Echarts

language-javascript
1
2
3
4
5
6
7
8
9
import {
createApp } from 'vue'
import App from './App.vue'

import * as echarts from 'echarts'

const app = createApp(App)
app.config.globalProperties.$echarts = echarts // 全局挂载echarts
app.mount('#app')

3.Vue setup组合式语法使用案例

language-html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<template>
<!-- 通过ref获取html元素 宽高必须设置 -->
<el-row>
<el-col :offset="8" :span="8">
<div ref="info" style="width: 100%; height: 600px"></div>
</el-col>
</el-row>
</template>
<script setup>
import {
onMounted, ref, inject } from "vue";
const {
proxy } = getCurrentInstance()//获取Vue3全局配置
const info = ref();//用来获取对应标签组件

onMounted(() => {

var infoEl = info.value;//获取ref="info"的标签组件
var userEc = proxy.$echarts.init(infoEl, "light");//proxy.$echarts是在获取全局配置中的echarts,这样就不需要在每个vue中import echarts了

//此处为图表配置区,可参考Echarts官网替换各种图表
var option = {

tooltip: {

trigger: 'item'
},
legend: {

top: '5%',
left: 'center'
},
series: [
{

name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {

borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {

show: false,
position: 'center'
},
emphasis: {

label: {

show: true,
fontSize: 40,
fontWeight: 'bold'
}
},
labelLine: {

show: false
},
data: [
{
value: 1048, name: 'Search Engine' },
{
value: 735, name: 'Direct' },
{
value: 580, name: 'Email' },
{
value: 484, name: 'Union Ads' },
{
value: 300, name: 'Video Ads' }
]
}
]
};
userEc.setOption(option);//将图标挂载到标签组件
});
</script>

(完)

Vue3 setup组合式语法优雅地使用Echarts库

https://xiamu-ssr.github.io/Hexo/2023/10/28/2023-H2/2023-10-28-22-20-16/

作者

Xiamu

发布于

2023-10-28

更新于

2024-08-11

许可协议

评论