问题描述
vue3中在main.Js已经全局引入了echarts,但在组件初始化还是找不到
./main.js文件
//引入echarts
// @ts-ignore
import * as echarts from 'echarts';
const app = createApp(App, {});
// 将 echarts 挂载到全局
app.config.globalProperties.$echarts = echarts;
./echarts.vue组件
<script lang="ts" setup>
const myChart = ref();
const option = ref({});
const data = reactive<object[]>([]);
const titlename = reactive<object[]>([]);
const initChart = () => {
myChart.value = echarts.init(
document.getElementById('zhuangTaiTongJi') as HTMLElement
);
option.value = {}
};
</script>
<template>
<div class="item_echart" id="zhuangTaiTongJi"></div>
</template>
<style lang="scss" scoped>
.item_echart {
width: 100%;
height: 100%;
}
</style>
原因分析:
提示:明明已经全局引入,组件中确找不到说明实例引入失败,或者是生命周期问题方向
在Vue 3中,尽管你已经在main.js
中通过app.config.globalProperties.$echarts = echarts;
将ECharts挂载到了全局,但在组件内直接使用echarts
是不可行的,因为没有直接暴露在全局作用域。在Vue 3的Composition API组件中,不能像Vue 2那样直接通过this.$echarts
访问全局属性。应该使用getCurrentInstance
来获取实例,然后访问globalProperties,
解决方案:
提示:在组件中获取全局属性
<script lang="ts" setup>
import { getCurrentInstance, reactive, ref, onMounted } from 'vue';
// 通过 internalInstance.appContext.config.globalProperties 获取全局属性或方法
let internalInstance: any = getCurrentInstance();
let echarts = internalInstance.appContext.config.globalProperties.$echarts;
const myChart = ref();
const option = ref({});
const data = reactive<object[]>([]);
const titlename = reactive<object[]>([]);
const initChart = () => {
myChart.value = echarts.init(
document.getElementById('zhuangTaiTongJi') as HTMLElement
);
option.value = {}
};