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

1. 安装Echarts

npm或者yarn安装

npm install echarts
yarn add echarts

2.main.js全局挂载Echarts

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组合式语法使用案例

<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>

(完)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值