我正在尝试在我的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));但在这种情况下,我的日志返回undefined
发布于 2021-05-27 01:21:59
ApexCharts需要在VueApexCharts之前加载,因此您需要确保Promises的脚本加载顺序。CDN脚本分别定义了window.ApexCharts和window.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))https://stackoverflow.com/questions/67707645
复制相似问题