在vue3加ts项目中引入Echarts

526 阅读2分钟

今天学习了一下在vue3加ts项目中使用Echarts,为了日后的开发做准备。

首先要使用 npm i -s echarts 指令安装Echarts。

我使用的方法是全局引入,要先在main.ts引入Echarts,这样就可以在各个组件使用Echarts而不用重复引入。

import { createApp } from 'vue';
import * as echarts from 'echarts';  //这两行是必须

async function bootstrap() {  //bootstrap是你的函数名字
  const app = createApp(App);
 
  app.provide('$echarts', echarts);  //这两行是必须

  app.mount('#app', true);
}

接下来在组件中使用Echarts

<template>
  <div ref="chartRef" :style="{ width: '800px', height: '400px' }"></div>
  <div ref="chartRef2" :style="{ width: '800px', height: '400px' }"></div>
</template>

<script setup lang="ts">
  import { inject, onMounted, ref } from 'vue';

  const echarts = inject('$echarts'); //通过这行代码引入echarts

  const chartRef = ref<HTMLDivElement | null>(null);
  const chartRef2 = ref<HTMLDivElement | null>(null);

  onMounted(() => {
    // const dom = document.getElementById('myChart');
    // const myChart = echarts.init(dom);
    if (chartRef.value && echarts) {
      const myChart = echarts.init(chartRef.value);

      const option = {
        title: {
          text: 'Stacked Line',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine'],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: 'Email',
            type: 'line',
            stack: 'Total',
            data: [120, 132, 101, 134, 90, 230, 210],
          },
          {
            name: 'Union Ads',
            type: 'line',
            stack: 'Total',
            data: [220, 182, 191, 234, 290, 330, 310],
          },
          {
            name: 'Video Ads',
            type: 'line',
            stack: 'Total',
            data: [150, 232, 201, 154, 190, 330, 410],
          },
          {
            name: 'Direct',
            type: 'line',
            stack: 'Total',
            data: [320, 332, 301, 334, 390, 330, 320],
          },
          {
            name: 'Search Engine',
            type: 'line',
            stack: 'Total',
            data: [820, 932, 901, 934, 1290, 1330, 1320],
          },
        ],
      };
      // 设置实例参数
      myChart.setOption(option);
    }

    const myChart2 = echarts.init(chartRef2.value);
    let base = +new Date(1968, 9, 3);
    let oneDay = 24 * 3600 * 1000;
    let date = [];
    let data = [Math.random() * 300];
    for (let i = 1; i < 20000; i++) {
      var now = new Date((base += oneDay));
      date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
      data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]));
    }
    const option2 = {
      tooltip: {
        trigger: 'axis',
        position: function (pt) {
          return [pt[0], '10%'];
        },
      },
      title: {
        left: 'center',
        text: 'Large Area Chart',
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
          },
          restore: {},
          saveAsImage: {},
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: date,
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%'],
      },
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 10,
        },
        {
          start: 0,
          end: 10,
        },
      ],
      series: [
        {
          name: 'Fake Data',
          type: 'line',
          symbol: 'none',
          sampling: 'lttb',
          itemStyle: {
            color: 'rgb(255, 70, 131)',
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgb(255, 158, 68)',
              },
              {
                offset: 1,
                color: 'rgb(255, 70, 131)',
              },
            ]),
          },
          data: data,
        },
      ],
    };

    myChart2.setOption(option2);
  });
</script>

具体代码代表的意思我还不清楚,现在只是确保代码可以跑起来后续根据开发需求进行修改。