Vue项目通过CDN引入ApexCharts后无法注册调用问题求解
问题原因
- 当前使用的vue-apexcharts CDN链接默认加载的是ES模块版本,该版本不会主动将库实例挂载到window对象上,因此无法通过
window.VueApexCharts拿到对应引用。 - vue-apexcharts版本和项目Vue版本不匹配也会导致挂载失败:Vue2项目需使用vue-apexcharts 1.x版本,Vue3项目需使用3.x及以上版本。
解决方法
- 将vue-apexcharts的CDN链接替换为对应版本的UMD格式资源链接:
- Vue2场景替换为:
https://cdn.jsdelivr.net/npm/vue-apexcharts@1.6.2/dist/vue-apexcharts.min.js - Vue3场景替换为对应3.x版本的UMD资源即可
- Vue2场景替换为:
- 可在初始化逻辑中增加属性存在性判断,避免运行异常,调整后的完整代码如下:
import Vue from "vue"; const loadScript = (src) => new Promise((resolve, reject) => { const script = document.createElement("script"); script.setAttribute("src", src); script.onload = resolve; script.onerror = reject; document.head.appendChild(script); }); const loadApexCharts = () => loadScript("https://cdn.jsdelivr.net/npm/apexcharts@3.36.3/dist/apexcharts.min.js"); const loadVueApexCharts = () => // 此处为Vue2对应的UMD资源链接 loadScript("https://cdn.jsdelivr.net/npm/vue-apexcharts@1.6.2/dist/vue-apexcharts.min.js"); const initVue = () => { // 先判断挂载是否成功 if (window.VueApexCharts) { Vue.component("apexcharts", window.VueApexCharts); } new Vue({ data: {}, components: {}, created() { console.log(window.VueApexCharts, 'log') }, }); }; loadApexCharts() .then(loadVueApexCharts) .then(initVue) .catch((err) => console.warn(err));
使用说明
全局注册完成后,直接在任意Vue组件中使用<apexcharts>标签即可,组件props、配置项和官方用法完全一致。
内容的提问来源于stack exchange,提问作者smuckert
相关产品推荐
相关产品推荐

