vue3集成echarts最佳实践

news/2025/2/13 6:25:36/

安装 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<divref='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<divref='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的Hooklet 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-ignorechart.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 = echartsapp.mount('#app')

在 tsx 页面中使用

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


http://www.ppmy.cn/news/1015001.html

相关文章

【Matlab】RBF神经网络遗传算法(RBF-GA)函数极值寻优——非线性函数求极值

上一篇博客介绍了GRNN神经网络遗传算法(GRNN-GA)函数极值寻优——非线性函数求极值&#xff0c;神经网络用的是RBF神经网络&#xff0c;RBF神经网络和GRNN神经网络有相似之处。本篇博客将GRNN神经网络替换成RBF神经网络&#xff0c;希望能帮助大家快速入门RBF网络。 1.背景条件…

GWJDN-400型2MHZ自动平衡高温介电温谱仪

GWJDN-400型2MHZ自动平衡高温介电温谱仪 关键词&#xff1a;介电常数&#xff0c;高温介电&#xff0c;自动平衡 主要功能&#xff1a; 材料介电常数测试仪 半导体材料的介电常数、导电率和C-V特性液晶材料:液晶单元的介电常数、弹性常数等C-V特性 性能特点: 温度&#xf…

Spring IoC (控制反转)

IoC 是 Inversion of Control 的简写&#xff0c;译为“控制反转”&#xff0c;它不是一门技术&#xff0c;而是一种设计思想&#xff0c;是一个重要的面向对象编程法则。 Spring 通过 IoC 容器来管理所有 Java 对象的实例化和初始化&#xff0c;控制对象与对象之间的依赖关系。…

nacos升级开启鉴权后,微服务无法连接的解决方案

版本&#xff1a; 软件版本号备注spring boot2.2.5.RELEASEspring-cloudHoxton.SR3spring-cloud-alibaba2.2.1.RELEASEnacos2.0.1从1.4.2版本进行升级。同时作为注册中心和配置中心 一、升级nacos版本&#xff0c;开启鉴权 1.在application.properties配置文件开启鉴权&…

C# 有效的字母异位词

242 有效的字母异位词 给定两个字符串 和 &#xff0c;编写一个函数来判断 是否是 的字母异位词。stts 注意&#xff1a;若 和 中每个字符出现的次数都相同&#xff0c;则称 和 互为字母异位词。stst 示例 1: 输入: s “anagram”, t “nagaram” 输出: true 示例 2: 输…

【C++】STL——priority_queue优先级队列的介绍和使用、priority_queue的其他成员函数使用

文章目录 1.priority_queue的介绍2.priority_queue的使用&#xff08;1&#xff09;priority_queue() 构造一个空的优先级队列 &#xff08;2&#xff09;priority_queue(first,last) 通过迭代器构造优先级队列&#xff08;3&#xff09;empty( )检测优先级队列是否为空&#x…

UE5.2 LyraDemo源码阅读笔记(四)

上一篇&#xff08;三&#xff09;讲到在模式玩法UI点击Elimination进入淘汰赛模式。 UI选择点击Elimination后&#xff0c;触发蓝图W_HostSessionScreen的HostSession节点&#xff0c;有&#xff1a; 调用这个方法切换关卡后&#xff0c;会调用到LyraGameMode.cpp的 ALyraGam…

解决GitHub的速度很慢的几种方式

1. GitHub 镜像访问 这里提供两个最常用的镜像地址&#xff1a; https://hub.njuu.cf/search https://www.gitclone.com/gogs/search/clonesearch 也就是说上面的镜像就是一个克隆版的 GitHub&#xff0c;你可以访问上面的镜像网站&#xff0c;网站的内容跟 GitHub 是完整同步…