前言

在我们使用vue3.x的时候,有些特性还是跟vue2.x区别很大的,这里讲下echarts的使用和怎么定义和使用全局变量

vue2中是:Vue.prototype.$http = () => {}
vue3中是:const app = createApp({})
                app.config.globalProperties.$http = () => {}

一、定义和使用全局变量

1.定义

main.ts的代码:定义一个全局echarts

import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
import router from './router/index';
import store from "./store/index"
import * as echarts from 'echarts';


const app = createApp(App)
app.config.globalProperties.$echarts = echarts
app.use(ElementPlus)
app.use(router)
app.use(store)
app.mount('#app')

2.使用

1.先引入getCurrentInstance

import {getCurrentInstance} from "vue";

2.实例化
这里要注意的是,这个变量名一定得是proxy,不能是像有些说的是ctx,否则的话是获取不到的,后面的括号也要加

const { proxy } = (getCurrentInstance() as any)

3.完整代码(使用echarts)

import {
  onMounted,
  ref,
  reactive,
  defineComponent,
  getCurrentInstance,
} from "vue";
export default defineComponent({
  name: "Home",
  setup() {
    const { proxy } = (getCurrentInstance() as any)

    onMounted(() => {
      let positionTop5_option = {
        barWidth: 20,
        color: "#4CA6FE",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        xAxis: {
          type: "category",
          data: ["前端", "后端", "产品", "ui设计", "IOS开发"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: [120, 200, 150, 80, 70],
            type: "bar",
            itemStyle: {
              normal: {
                color: new proxy.$echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#7BAAF3' }, // 柱图渐变色
                    { offset: 1, color: '#9966FD' } // 柱图渐变色
                  ]
                )
              },
              emphasis: {
                color: new proxy.$echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#7BAAF3' }, // 柱图高亮渐变色
                    { offset: 1, color: '#9966FD' } // 柱图高亮渐变色
                  ]
                )
              }
            }
          },
        ],
      };
      
      let chartDom = document.getElementById("positionTop5");
      let chart1 = proxy.$echarts.init(chartDom);
      chart1.setOption(positionTop5_option);
    });

    return {};
  },
});
Logo

前往低代码交流专区

更多推荐