首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Vue中使用导入为CDN的ApexCharts

在Vue中使用导入为CDN的ApexCharts
EN

Stack Overflow用户
提问于 2021-05-26 23:03:52
回答 1查看 189关注 0票数 0

我正在尝试在我的Vue项目中使用vue-apexcharts,并且我正在尝试通过脚本标记导入库,以便在构建我的应用程序时保持较小的包大小。

我的代码看起来像这样:

从“Vue”导入vue;

代码语言:javascript
复制
export default new Vue({
  data: {},
  components: {},
  created() {
    const apexcharts = document.createElement("script");
    apexcharts.setAttribute("src", "https://cdn.jsdelivr.net/npm/apexcharts");
    document.head.appendChild(apexcharts);

    const vueApexcharts = document.createElement("script");
    vueApexcharts.setAttribute("src", "https://cdn.jsdelivr.net/npm/vue-apexcharts");
    document.head.appendChild(vueApexcharts);
   
  },
});

添加了脚本标记后,我不确定如何注册apexcharts并在组件中使用它。通常,我会在全局窗口中找到库引用,但在那里找不到任何东西。

提前感谢!

编辑

我正在尝试实现这样的目标:

代码语言:javascript
复制
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");
const loadVueApexCharts = () =>
  loadScript("https://cdn.jsdelivr.net/npm/vue-apexcharts");

const initVue = () => {
  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));

但在这种情况下,我的日志返回undefined

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-27 01:21:59

ApexCharts需要在VueApexCharts之前加载,因此您需要确保Promises的脚本加载顺序。CDN脚本分别定义了window.ApexChartswindow.VueApexCharts,因此脚本加载完成后,您可以注册apexcharts组件以在应用中使用:

代码语言:javascript
复制
// main.js
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')
const loadVueApexCharts = () => loadScript('https://cdn.jsdelivr.net/npm/vue-apexcharts')

const initVue = () => {
  Vue.component('apexcharts', window.VueApexCharts)
  new Vue({
    render: (h) => h(App)
  }).$mount('#app')
}

loadApexCharts()
  .then(loadVueApexCharts)
  .then(initVue)
  .catch((err) => console.warn(err))

demo

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67707645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档