在vue3 中使用echarts

1,安装echarts

npm install echarts --save

有cnpm 的可以cnpm安装

2,在main.js中导入

import { createApp } from 'vue'
import App from './App.vue'
import * as echarts from 'echarts'

const app = createApp(App).mount('#app')
app.echarts=echarts

3,在需要使用的页面,定义div

4,在monted中init

mounted() {
    //this.$root => app
    let myChart = this.$root.echarts.init(
      document.getElementById("myChart")
    );
    // 绘制图表
    myChart.setOption({
      title: { text: "总用户量" },
      tooltip: {},
      xAxis: {
        data: ["12-3", "12-4", "12-5", "12-6", "12-7", "12-8"],
      },
      yAxis: {},
      series: [
        {
          name: "用户量",
          type: "line",
          data: [5, 20, 36, 10, 10, 20],
        },
      ],
    });
  },

这里最重要的是import * as echarts from 'echarts', 不能 import echarts from 'echarts',这样会报错,因为5,0版本的echarts的接口已经变成了下面这样

export { EChartsFullOption as EChartsOption, connect, disConnect, dispose, getInstanceByDom, getInstanceById, getMap, init, registerLocale, registerMap, registerTheme };

 

 

在SetUp中使用echarts

 

因为setup中没有this,而且这时候还没有渲染,所以在setup中 ,可以使用provide/inject来把echart引入进来

 

在根组件里引入echart,一般是App.vue

App.vue:

import * as echarts from 'echarts'
import { provide } from 'vue'

export default {
  name: 'App',
  setup(){
    provide('ec',echarts)//provide
  },
  components: {
  }
}

之后在需要的页面中inject

 

data_page.vue:

import { inject, onMounted } from "vue";

export default {
  name: "data_page",
  setup() {
    let echarts = inject("ec");//引入
    onMounted(() => {//需要获取到element,所以是onMounted的Hook
      let myChart = echarts.init(document.getElementById("customerChart"));
      // 绘制图表
      myChart.setOption({
        title: { text: "总用户量" },
        tooltip: {},
        xAxis: {
          data: ["12-3", "12-4", "12-5", "12-6", "12-7", "12-8"],
        },
        yAxis: {},
        series: [
          {
            name: "用户量",
            type: "line",
            data: [5, 20, 36, 10, 10, 20],
          },
        ],
      });
      window.onresize = function () {//自适应大小
        myChart.resize();
      };
    });
  },
  components: {},
  mounted() {},
};

 

 

你可能感兴趣的:(js,vue,echarts,javascript,前端)