You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Nuxt中使用vue-chart-3如何实现饼图扇区显示百分比值

问题原因

vue-chart-3 底层基于 Chart.js v3+ 版本,你所使用的 pieceLabel 是Chart.js v2版本的第三方插件配置项,在v3及以上版本中已废弃,所以配置不会生效,必须使用 chartjs-plugin-datalabels 插件实现该需求。

具体实现步骤

  • 第一步:安装依赖
npm install chartjs-plugin-datalabels
# 或者使用yarn
yarn add chartjs-plugin-datalabels
  • 第二步:修改组件代码,引入并注册插件,调整配置项
<template>
  <div style="width: 100%">
    <DoughnutChart :chart-data="testData" :options="options" :plugins="plugins" />
  </div>
</template>
<script>
import { defineComponent, ref } from '@vue/composition-api'
import { DoughnutChart } from 'vue-chart-3'
// 引入datalabels插件
import DataLabelsPlugin from 'chartjs-plugin-datalabels'

export default defineComponent({
  name: 'Home',
  components: { DoughnutChart },
  setup () {
    // 注册插件
    const plugins = [DataLabelsPlugin]
    
    const testData = {
      labels: ['Paris', 'Nîmes', 'Toulon', 'Perpignan', 'Autre'],
      datasets: [
        {
          data: [30, 40, 60, 70, 5],
          backgroundColor: ['red', '#0079AF', '#123E6B', '#97B0C4', '#A5C8ED']
        }
      ]
    }
    const options = ref({
      responsive: true,
      plugins: {
        // 配置datalabels插件
        datalabels: {
          color: '#fff',
          // 格式化显示百分比
          formatter: (val, ctx) => {
            const total = ctx.chart.data.datasets[0].data.reduce((a,b) => a + b, 0)
            const percentage = ((val / total) * 100).toFixed(1)
            return `${percentage}%`
          }
        }
      }
    })

    return { testData, options, plugins }
  }
})
</script>

配置说明

你可以根据需求调整datalabels下的其他属性,常用配置项如下:

  • font.size:调整数值字体大小
  • anchor:数值锚点位置,可选值center/end/start
  • align:数值对齐方式,可选值center/top/bottom/left/right

内容的提问来源于stack exchange,提问作者MohammadAmin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:36:06