vue3中按需全局引入echarts

目录

npm i echarts

使用install插件将echarts注册为全局属性

main.js中使用该插件

 通过proxy使用即可


  • npm i echarts

  • 使用install插件将echarts注册为全局属性

下面的代码是按需引入,代码官网上有,也可以 import * as echarts from 'echarts'进行全局引入

// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core'
// 引入柱状图图表,图表后缀都为 Chart,用什么引入什么
import { BarChart, LineChart } from 'echarts/charts'
// 引入标题,提示框,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components'
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers'

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
])
//用插件注册为全局实例属性
export default {
  install: app => {
    app.config.globalProperties.$echarts = echarts
  }
}
  • main.js中使用该插件

import echartsPlugin from '@/utils/echarts'
app.use(echartsPlugin)
  •  通过proxy使用即可

    <script setup>
    import { getCurrentInstance, onMounted, ref } from 'vue'
    const { proxy } = getCurrentInstance() // 获取当前实例
    const chartRef = ref(null)
    onMounted(() => {
      const chart = proxy.$echarts.init(chartRef.value)
      const option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            type: 'line',
            data: [820, 932, 901, 934, 1290, 1330, 1320]
          }
        ]
      }
      chart.setOption(option)
    })
    </script>
    
    <template>
      <!-- 一级路由出口 -->
      <router-view></router-view>
      <div ref="chartRef" class="chart"></div>
    </template>
    
    <style scoped>
    .chart {
      width: 100%;
      height: 300px;
      border: 1px solid #ccc;
    }
    </style>

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值