我必须为支付网关使用两个外部脚本。
现在两者都放在index.html文件中。
但是,我不想在开头本身就加载这些文件。
只有在用户打开特定组件(使用路由器视图)时才需要支付网关。
有办法实现这个目标吗?
谢谢。
我必须为支付网关使用两个外部脚本。
现在两者都放在index.html文件中。
但是,我不想在开头本身就加载这些文件。
只有在用户打开特定组件(使用路由器视图)时才需要支付网关。
有办法实现这个目标吗?
谢谢。
当前回答
更新:这不再工作在Vue 3。你会收到这样的错误:
VueCompilerError:在客户端组件模板中忽略带有副作用(和)的标签。
如果你试图将外部js脚本嵌入vue.js组件模板,请遵循以下步骤:
我想向我的组件添加一个外部JavaScript嵌入代码,如下所示:
<template>
<div>
This is my component
<script src="https://badge.dimensions.ai/badge.js"></script>
</div>
<template>
Vue显示了这个错误:
模板应该只负责将状态映射到UI。避免在模板中放置带有副作用的标记,例如,因为它们不会被解析。
我解决这个问题的方法是通过添加type="application/javascript"(参见这个问题了解更多关于js的MIME类型):
<script type="application/javascript" defer src="…"" > < > /脚本
您可能会注意到defer属性。如果你想了解更多,请观看Kyle的视频
其他回答
您可以使用vue-loader并在它们自己的文件中编写组件(单文件组件)。这将允许您在组件的基础上包含脚本和css。
您是否正在使用vue的Webpack入门模板(https://github.com/vuejs-templates/webpack)?vue-loader (https://github.com/vuejs/vue-loader)已经设置好了。如果你不使用启动器模板,你必须设置webpack和vue-loader。
然后,您可以将脚本导入到相关的(单个文件)组件。在此之前,你必须从脚本中导出你想导入到组件中的内容。
ES6进口: ——https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import ——http://exploringjs.com/es6/ch_modules.html
~编辑~ 你可以从这些包装器中导入: ——https://github.com/matfish2/vue-stripe ——https://github.com/khoanguyen96/vue-paypal-checkout
在Vue 3中,我使用mejiamanuel57回答,并附加了一个检查,以确保脚本标记尚未加载。
mounted() {
const scripts = [
"js/script1.js",
"js/script2.js"
];
scripts.forEach(script => {
let tag = document.head.querySelector(`[src="${ script }"`);
if (!tag) {
tag = document.createElement("script");
tag.setAttribute("src", script);
tag.setAttribute("type", 'text/javascript');
document.head.appendChild(tag);
}
});
// ...
解决这个问题的一个简单而有效的方法是将外部脚本添加到组件的vue mounted()中。我将用谷歌Recaptcha脚本为您演示:
<template>
.... your HTML
</template>
<script>
export default {
data: () => ({
......data of your component
}),
mounted() {
let recaptchaScript = document.createElement('script')
recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
document.head.appendChild(recaptchaScript)
},
methods: {
......methods of your component
}
}
</script>
来源:https://medium.com/@lassiuosukainen how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8
使用webpack和vue加载器,你可以这样做
在创建组件之前,它会等待外部脚本加载,因此在组件中可以使用globar vars等
components: {
SomeComponent: () => {
return new Promise((resolve, reject) => {
let script = document.createElement('script')
script.onload = () => {
resolve(import(someComponent))
}
script.async = true
script.src = 'https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places'
document.head.appendChild(script)
})
}
},