Nuxt3 使用echarts

    124

Nuxt3使用echarts

因为Nuxt3是一个SSR框架,所以在引入的时候有些许不同。

安装echarts和vue-echarts

因为nuxt3是基于vue3的,所以演示只有vue3的版本~

npm install echarts vue-echarts

使用nuxt的插件系统导入echarts 以及 vue-echarts

Nuxt3 会自动导入根目录下的plugins文件夹内容,无需手动引入。

所以编写一个文件,echarts.js

import { use, registerMap } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, PieChart,ScatterChart, EffectScatterChart } from 'echarts/charts';

import { GridComponent,GeoComponent, LegendComponent,TitleComponent, TooltipComponent,
   } from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import VChart, { THEME_KEY } from 'vue-echarts';
import china from "~/utils/china.json"
/**
 * 按需注册 ECharts 组件
 */
export default defineNuxtPlugin((nuxtAPP) => {
  const { vueApp } = nuxtAPP;
  vueApp.component('VChart', VChart);
  vueApp.provide(THEME_KEY, 'light');
  use([
    ScatterChart,
    EffectScatterChart,
    GeoComponent,
    CanvasRenderer,
    PieChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent,
    LineChart,
    UniversalTransition,
    LabelLayout,
  ]);
  //@ts-ignore
  registerMap('china', china);
});

使用

因为我们注册插件是在plugins中直接注册的,所以不需要在组件中重新定义~

<template>
  <v-chart class="chart" :option="option" />
</template>
<script setup>
const option = ref({
  title: {
    text: "Traffic Sources",
    left: "center"
  },
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b} : {c} ({d}%)"
  },
  legend: {
    orient: "vertical",
    left: "left",
    data: ["Direct", "Email", "Ad Networks", "Video Ads", "Search Engines"]
  },
  series: [
    {
      name: "Traffic Sources",
      type: "pie",
      radius: "55%",
      center: ["50%", "60%"],
      data: [
        { value: 335, name: "Direct" },
        { value: 310, name: "Email" },
        { value: 234, name: "Ad Networks" },
        { value: 135, name: "Video Ads" },
        { value: 1548, name: "Search Engines" }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      }
    }
  ]
});
</script>

就这样就可以直接使用了~

在线样例

访问IP位置统计

消息盒子

# 暂无消息 #

只显示最新10条未读和已读信息