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

Vue3与vue-chartjs柱状图无法显示,如何仅在main.js中修复?

解决Vue运行时编译警告并在main.js中显示柱状图

问题原因

你遇到的警告是因为默认Vue使用的是运行时版本,不支持在组件选项中直接使用template字符串进行编译,必须改用渲染函数,或者配置打包工具让Vue使用支持完整编译的版本。

方案一:使用渲染函数(仅修改main.js)

将组件中的template选项替换为Vue的渲染函数(h函数),无需修改任何配置文件,仅改动main.js即可解决问题:

import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip } from 'chart.js'
import { createApp, h } from 'vue'
import { Bar } from 'vue-chartjs'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

const BarChart = {
    name: 'BarChart',
    components: { Bar },
    data() {
        return {
            chartData: {
                labels: ['January', 'February', 'March'],
                datasets: [
                    {
                        label: 'Data One',
                        backgroundColor: '#f87979',
                        data: [40, 20, 12]
                    }
                ]
            }
        }
    },
    // 替换template为render函数,通过h函数创建Bar组件实例
    render() {
        return h(Bar, {
            props: {
                data: this.chartData
            }
        })
    }
}
createApp(BarChart).mount('#app')

方案二:配置打包工具使用完整编译版Vue(需修改配置文件)

如果坚持要使用template选项,可以修改项目的打包配置,将Vue别名指向支持编译的版本:

Vite项目(修改vite.config.js)

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      'vue': 'vue/dist/vue.esm-bundler.js'
    }
  }
})

Vue CLI(webpack)项目(修改vue.config.js)

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm-bundler.js'
      }
    }
  }
}

修改配置后,你原来的main.js代码即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:10:20