【问题标题】:Using ApexCharts imported as CDN in Vue在 Vue 中使用作为 CDN 导入的 ApexCharts
【发布时间】:2021-05-27 02:21:17
【问题描述】:

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

我的代码如下所示:

从“vue”导入Vue;

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 并在组件中使用它。通常我会在全局窗口中找到库引用,但在那里找不到任何东西。

提前致谢!

编辑

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

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));

但在这种情况下我的日志返回未定义

【问题讨论】:

    标签: vue.js cdn apexcharts


    【解决方案1】:

    ApexCharts 需要在 VueApexCharts 之前加载,所以你必须用Promises 保证脚本加载顺序。 CDN 脚本分别定义了window.ApexChartswindow.VueApexCharts,因此一旦脚本加载完毕,您就可以注册apexcharts 组件以在应用中使用:

    // 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

    【讨论】:

      猜你喜欢
      • 2020-08-03
      • 2020-04-25
      • 2020-06-25
      • 2022-11-11
      • 1970-01-01
      • 2021-01-10
      • 2019-04-16
      • 1970-01-01
      • 2018-12-04
      相关资源
      最近更新 更多