安装 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)}