1.下载 echarts

npm i -s echarts

2.在main.js中引入

import { createApp } from 'vue'
import App from './App.vue'

// 引入 echarts
import * as echarts from 'echarts'
const app = createApp(App)
// 全局挂载 echarts
app.config.globalProperties.$echarts = echarts

app.mount('#app')

3.方式一:vue3.0的写法,在组件中使用

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

<script>
import { getCurrentInstance, onMounted } from 'vue';

export default {
  setup() {
    // 通过 internalInstance.appContext.config.globalProperties 获取全局属性或方法
    let internalInstance = getCurrentInstance();
    let echarts = internalInstance.appContext.config.globalProperties.$echarts;

    onMounted(() => {
      const dom = document.getElementById('myChart');
      const myChart = echarts.init(dom); // 初始化echarts实例
      const option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true
          }
        ]
      };
      // 设置实例参数
      myChart.setOption(option);
    });
    return {};
  }
};
</script>

4:方式二:全局挂载后,在组件中以 vue2 的写法

<template>
  <div
    ref="myChart"
    id="myChart"
    :style="{ width: '800px', height: '400px' }"
  ></div>
</template>
<script>
export default {
  mounted() {
    this.drawLine();
  },
  methods: {
    drawLine() {
      const dom = this.$refs['myChart'];
      const myChart = this.$echarts.init(dom); // 初始化echarts实例
      const option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line',
            smooth: true
          }
        ]
      };
      // 设置实例参数
      myChart.setOption(option);
    }
  }
};
</script>

5.方式三:直接在组件中引入echarts

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

<script>
// 方式二:直接在组件中引入echarts
import * as echarts from 'echarts';
export default {
  mounted() {
    const dom = this.$refs['myChart']; // 获取dom节点
    const myChart = echarts.init(dom); // 初始化echarts实例

    const option = {
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [820, 932, 901, 934, 1290, 1330, 1320],
          type: 'line',
          smooth: true
        }
      ]
    };
    // 设置实例参数
    myChart.setOption(option);
  }
};
</script>

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐