vue3集成echarts最佳实践

安装 echarts

npm install echarts --save

两种引用方式

非虚拟 dom
import * as echarts from 'echarts';

var chartDom = document.getElementById('mychart');
var myChart = echarts.init(chartDom);
var option;

option = {
  title: {
    text: 'Referer of a Website',
    subtext: 'Fake Data',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 1048, name: 'Search Engine' },
        { value: 735, name: 'Direct' },
        { value: 580, name: 'Email' },
        { value: 484, name: 'Union Ads' },
        { value: 300, name: 'Video Ads' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

option && myChart.setOption(option);

------ tsx 或者 template

   <div
                ref='pieChartRef'
                id={'myChart'}
                style={{
                    height: "300px",
                    width: typeof width === 'number' ? width + 'px' : width
                }}
            >

      </div>
虚拟 dom (推荐使用)
import * as echarts from 'echarts'
const PieChart = defineComponent({
    name: 'PieChart',
    props,
    setup(props) {
        const pieChartRef: Ref<HTMLDivElement | null> = ref(null)

        const top10 = () => {
            return props.data.length>=10 ? props.data.slice(0,10) : props.data
        }

        const option = {
            title: {
                text: '分组聚合 Top 10',
                left: 'center',
                textStyle: {
                   color:'white'
                },
            },
            tooltip: {
                trigger: 'item',
                backgroundColor: '#fff'
            },
            legend: {
                bottom: '0%',
                left: 'center',
                textStyle:{
                    fontSize: 16,
                    color: 'white',
                    fontWeight: 'bold'
                }
            },
            series: [
                {
                    type: 'pie',
                    radius: ['35%', '60%'],
                    center: ['50%', '40%'],
                    avoidLabelOverlap: false,
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 30,
                            fontWeight: 'bolder',
                            color: 'white'
                        }
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    labelLine: {
                        show: false
                    },
                    data: top10()
                }
            ]
        }

        let chart:Ref<ECharts | null>  = ref(null)
        const init = () => {
            chart.value = echarts.init(pieChartRef.value)
            chart.value.setOption(option)
        }


        const resize = throttle(() => {
            chart && chart.value.resize()
        }, 20)


        watch(
            () => props.data,
            () => {
                option.series[0].data= top10()
                chart.value.setOption(option)
            }
        )

        onMounted(() => {
            init()
            addEventListener('resize', resize)
        })


        return { pieChartRef }
    },
    render() {
        const { height, width } = this
        // console.log(`pie prop height:${height}, width:${width}`)
        return (
            // height: typeof height === 'number' ? height + 'px' : height,
            // width: typeof width === 'number' ? width + 'px' : width
            <div
                ref='pieChartRef'
                id={'myChart'}
                style={{
                    height: "300px",
                    width: typeof width === 'number' ? width + 'px' : width
                }}
            >

            </div>
        )
    }
})

三种与 Vue3 集成方式

单组件
import { onMounted } from "vue";
import * as echarts from 'echarts'
export default {
  name: "data_page",
  setup() {
    onMounted(() => {//需要获取到element,所以是onMounted的Hook
      let myChart = echarts.init(document.getElementById("customerChart"));
      // 绘制图表
      myChart.setOption({
        title: { text: "总用户量" },
        tooltip: {},
        xAxis: {
          data: ["12-3", "12-4", "12-5", "12-6", "12-7", "12-8"],
        },
        yAxis: {},
        series: [
          {
            name: "用户量",
            type: "line",
            data: [5, 20, 36, 10, 10, 20],
          },
        ],
      });
      window.onresize = function () {//自适应大小
        myChart.resize();
      };
    });
  },
  components: {},
  mounted() {},
};
全局 provide

在 App.vue种注入

<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import { useOsTheme, darkTheme ,GlobalThemeOverrides} from 'naive-ui'
import * as echarts from 'echarts'

provide('ec',echarts)//provide

</script>

<template>

  <NConfigProvider :theme="{useOsTheme}"  :theme-overrides="themeOverrides">
    <n-global-style/>
    <NMessageProvider>
    <router-view/>
    </NMessageProvider>
  </NConfigProvider>
</template>

<style lang="scss" scoped>

</style>

在组件中使用,这种方式可能会出现不能识别类型警告,需要加@ts-ignore

let echarts = inject("ec");//引入

            // @ts-ignore
            chart.value = echarts.init(pieChartRef.value)
全局挂载(推荐使用)

main.ts中配置如下:

import App from './App.vue'
import { createApp } from 'vue'
import './style.css'
//  echarts
import * as echarts from 'echarts'

const pinia = createPinia() 
pinia.use(piniaPluginPersistedstate) 

const app = createApp(App)
// 挂载 echarts
app.config.globalProperties.echarts = echarts

app.mount('#app')

在 tsx 页面中使用

        const globalProperties = getCurrentInstance()?.appContext.config.globalProperties
        let chart:Ref<ECharts | null>  = ref(null)
        const init = () => {
            chart.value = globalProperties?.echarts.init(pieChartRef.value)
            chart.value.setOption(option)
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3 是一个流行的 JavaScript 框架,而 ECharts 是一个基于 JavaScript 的数据可视化库,可用于创建各种图表和图形。Vue3 和 ECharts 可以很好地集成,因为它们都是基于 JavaScript 的。你可以使用 Vue3 的组件化开发来创建包含 ECharts 图表的交互式应用程序。以下是一些使用 Vue3 和 ECharts 的示例: 1. 在 Vue3 中使用 ECharts 进行数据可视化 使用 Vue3 和 ECharts 可以很容易地创建数据可视化应用程序。你可以将 ECharts 图表作为 Vue3 组件添加到你的应用程序中,然后使用 Vue3 的数据绑定和事件处理程序来实现动态交互。例如,你可以创建一个柱状图示例,当用户点击柱状图时,可以显示更多信息。 2. 使用 Vue3 和 ECharts 创建仪表板 使用 Vue3 和 ECharts 可以创建仪表板应用程序,在仪表板中显示各种图表和指标。你可以通过将 ECharts 图表作为 Vue3 组件添加到仪表板中来实现这一点。然后,你可以使用 Vue3 的路由和状态管理来实现导航和数据管理。 3. 将 ECharts 图表作为 Vue3 组件进行重用 你可以将 ECharts 图表作为可重用的 Vue3 组件进行封装,以便在多个应用程序中重复使用。然后,你可以使用 Vue3 的插槽和属性来自定义和配置每个实例的外观和行为。 总之,Vue3 和 ECharts 是两个非常强大的 JavaScript 工具,可以很好地结合使用,以创建出色的数据可视化应用程序和仪表板。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值