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

Vue3项目中引入及使用Plotly.js的完整流程咨询

Vue3 中 plotly.js 完整引入与使用流程

一、安装依赖

优先安装预打包的plotly.js-dist包,免去手动配置构建工具的麻烦:

npm install plotly.js-dist --save
# 或使用 yarn
yarn add plotly.js-dist

若需自定义构建(比如只引入部分图表类型),可安装核心包plotly.js,但需额外配置webpack/vite,新手推荐直接用plotly.js-dist。

二、引入方式

1. 全局引入(全项目可用)

在项目根目录的main.js中添加:

import { createApp } from 'vue'
import App from './App.vue'
import Plotly from 'plotly.js-dist'

const app = createApp(App)
// 挂载到全局属性,方便组件内调用
app.config.globalProperties.$Plotly = Plotly

app.mount('#app')

2. 局部引入(按需使用)

在需要使用的Vue组件中直接引入:

import Plotly from 'plotly.js-dist'

三、基础使用示例

选项式API组件示例

<template>
  <div ref="plotContainer" style="width: 800px; height: 600px;"></div>
</template>

<script>
export default {
  mounted() {
    const container = this.$refs.plotContainer
    // 图表数据
    const data = [
      {
        x: ['2024-01', '2024-02', '2024-03'],
        y: [10, 20, 15],
        type: 'scatter',
        mode: 'lines+markers',
        name: '月度数据'
      }
    ]
    // 布局配置
    const layout = {
      title: '基础折线图',
      xaxis: { title: '月份' },
      yaxis: { title: '数值' }
    }
    // 渲染图表
    this.$Plotly.newPlot(container, data, layout)
  },
  beforeUnmount() {
    // 组件销毁前清理图表,避免内存泄漏
    if (this.$refs.plotContainer) {
      this.$Plotly.purge(this.$refs.plotContainer)
    }
  }
}
</script>

Composition API(setup语法糖)示例

<template>
  <div ref="plotContainer" style="width: 800px; height: 600px;"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import Plotly from 'plotly.js-dist'

const plotContainer = ref(null)

onMounted(() => {
  if (!plotContainer.value) return
  const data = [
    {
      x: ['Jan', 'Feb', 'Mar'],
      y: [25, 30, 22],
      type: 'bar',
      name: '季度销量'
    }
  ]
  const layout = {
    title: '基础柱状图',
    xaxis: { title: '月份' },
    yaxis: { title: '销量' }
  }
  Plotly.newPlot(plotContainer.value, data, layout)
})

onBeforeUnmount(() => {
  if (plotContainer.value) {
    Plotly.purge(plotContainer.value)
  }
})
</script>

四、常见引入问题排查

  • 报错"Cannot find module 'plotly.js'":检查是否安装的是plotly.js而非plotly.js-dist,前者需额外配置构建工具loader,建议直接替换为plotly.js-dist。
  • 全局引入后组件内this.$Plotly为undefined:确认main.js已正确挂载到app.config.globalProperties;若用setup语法糖,需通过getCurrentInstance()获取全局属性:
    import { getCurrentInstance } from 'vue'
    const { appContext } = getCurrentInstance()
    const Plotly = appContext.config.globalProperties.$Plotly
    
  • 图表无法渲染:确保DOM容器已挂载(在onMounted中执行渲染),且容器设置了明确的宽高样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:00:08