繁体   English   中英

Vue.js 动态注入外部依赖

[英]Vue.js inject dynamically external dependencies

我在 vue.js 中有一个使用 vue-cli 的站点。 当应用程序启动时,/js/app.js 文件加载并执行 vue。 我通过在 index.html 中添加链接来加载依赖项,例如:

<script type="text/javascript" src="http://localhost:3001/lib.umd.min.js"></script>

此加载的依赖项,一切都很好。 我的问题是我事先不知道网址。 它们位于站点根目录下的 json 文件中,我必须读取该文件然后动态注入到站点中。 如果在 main.js 我做:

const head = document.getElementsByTagName('head')[0]
const script = document.createElement('script')
script.type = 'text/javascript'
script.onload = function () {
    new Vue({
        router,
        render: h => h(App)
    }).$mount('#app')
}
script.src = 'http://localhost:3001/lib.umd.min.js'
head.appendChild(script)

不理解依赖关系,但 html 中的链接存在。 App Vue 运行良好,但不是依赖项。

在您的应用程序的挂载钩子中尝试:

mounted() {
 // get the scripts from your file and loop if needed
 // then for each one... 
 let myScript = document.createElement('script')
 myScript.setAttribute('src', 'https://some-rl.js') // url from file goes here
 document.head.appendChild(myScript)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM