在Nuxt项目中使用ECharts可以快速实现数据可视化。nuxt-echarts模块为Nuxt提供了开箱即用的ECharts集成方案,本文将介绍完整的集成步骤。
使用Nuxt CLI快速添加echarts模块:
npx nuxi module add echarts
该命令会自动将nuxt-echarts添加到项目依赖并在nuxt.config.ts中注册模块。
在nuxt.config.ts中添加echarts配置,必须显式声明要使用的图表类型和组件:
export default defineNuxtConfig({
modules: [
'nuxt-echarts'
],
echarts: {
// 指定需要的图表类型
charts: ['PieChart', 'BarChart', 'LineChart'],
// 指定需要的组件
components: [
'DatasetComponent',
'GridComponent',
'TooltipComponent',
'LegendComponent',
'TitleComponent'
]
}
})
nuxt-echarts采用按需加载机制,只会打包你声明的图表和组件,未声明的功能将无法使用。使用<client-only>包裹图表组件,因为ECharts依赖浏览器环境:
<template>
<div>
<h1>图表示例</h1>
<client-only>
<VChart :option="option" style="height: 400px;" />
</client-only>
</div>
</template>
<script setup lang="ts">
import type { Option } from 'nuxt-echarts/runtime/types'
const option = ref<Option>({
title: {
text: '示例饼图'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left'
},
series: [
{
name: '访问来源',
type: 'pie',
radius: '50%',
data: [
{ value: 1048, name: '搜索引擎' },
{ value: 735, name: '直接访问' },
{ value: 580, name: '邮件营销' },
{ value: 484, name: '联盟广告' },
{ value: 300, name: '视频广告' }
]
}
]
})
</script>
<client-only>?<client-only>确保组件只在客户端渲染。nuxt-echarts提供了完整的类型支持,使用官方类型定义来实现option:
import type { Option } from 'nuxt-echarts/runtime/types'
// 示例:柱状图配置
const barOption = ref<Option>({
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar'
}
]
})
结合以上步骤的完整页面示例:
<template>
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold mb-4">销售数据分析</h1>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<!-- 饼图 -->
<div class="bg-white p-4 rounded shadow">
<client-only>
<VChart :option="pieOption" style="height: 400px;" />
</client-only>
</div>
<!-- 柱状图 -->
<div class="bg-white p-4 rounded shadow">
<client-only>
<VChart :option="barOption" style="height: 400px;" />
</client-only>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import type { Option } from 'nuxt-echarts/runtime/types'
const pieOption = ref<Option>({
title: { text: '销售渠道分布' },
tooltip: { trigger: 'item' },
legend: { orient: 'vertical', left: 'left' },
series: [{
name: '销售额',
type: 'pie',
radius: '50%',
data: [
{ value: 1048, name: '线上商城' },
{ value: 735, name: '实体店' },
{ value: 580, name: '代理商' }
]
}]
})
const barOption = ref<Option>({
title: { text: '月度销售趋势' },
tooltip: { trigger: 'axis' },
xAxis: {
type: 'category',
data: ['1月', '2月', '3月', '4月', '5月', '6月']
},
yAxis: { type: 'value' },
series: [{
data: [120, 200, 150, 80, 170, 210],
type: 'bar'
}]
})
</script>
nuxt.config.ts中声明了对应的图表类型和组件<client-only>包裹<script setup lang="ts">
const chartRef = ref()
// 监听窗口大小变化
useEventListener('resize', () => {
chartRef.value?.resize()
})
</script>
<template>
<client-only>
<VChart ref="chartRef" :option="option" style="height: 400px;" />
</client-only>
</template>
通过以上步骤,你就可以在Nuxt项目中轻松集成和使用ECharts图表了!
(注:文档内容由 Copilot 生成)