我必须为支付网关使用两个外部脚本。
现在两者都放在index.html文件中。
但是,我不想在开头本身就加载这些文件。
只有在用户打开特定组件(使用路由器视图)时才需要支付网关。
有办法实现这个目标吗?
谢谢。
我必须为支付网关使用两个外部脚本。
现在两者都放在index.html文件中。
但是,我不想在开头本身就加载这些文件。
只有在用户打开特定组件(使用路由器视图)时才需要支付网关。
有办法实现这个目标吗?
谢谢。
当前回答
您是否正在使用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
其他回答
来自mejiamanuel57的答案很好,但我想添加几个适合我的技巧(我花了几个小时在上面)。首先,我需要使用“窗口”范围。此外,如果您需要访问“onload”函数内的任何Vue元素,则需要为“this”实例创建一个新变量。
<script>
import { mapActions } from "vuex";
export default {
name: "Payment",
methods: {
...mapActions(["aVueAction"])
},
created() {
let paywayScript = document.createElement("script");
let self = this;
paywayScript.onload = () => {
// call to Vuex action.
self.aVueAction();
// call to script function
window.payway.aScriptFunction();
};
// paywayScript.async = true;
paywayScript.setAttribute(
"src",
"https://api.payway.com.au/rest/v1/payway.js"
);
document.body.appendChild(paywayScript);
}
};
</script>
我在Vue 2.6上使用它。这里有一个关于“let self = this;”在Javascript中如何工作的技巧的解释:
var that = this;在JavaScript中是什么意思?
您可以使用vue-loader并在它们自己的文件中编写组件(单文件组件)。这将允许您在组件的基础上包含脚本和css。
mounted() {
if (document.getElementById('myScript')) { return }
let src = 'your script source'
let script = document.createElement('script')
script.setAttribute('src', src)
script.setAttribute('type', 'text/javascript')
script.setAttribute('id', 'myScript')
document.head.appendChild(script)
}
beforeDestroy() {
let el = document.getElementById('myScript')
if (el) { el.remove() }
}
为了保持组件的干净,你可以使用mixin。
在组件上导入外部mixin文件。
Profile.vue
import externalJs from '@client/mixins/externalJs';
export default{
mounted(){
this.externalJsFiles();
}
}
externalJs.js
import('@JSassets/js/file-upload.js').then(mod => {
// your JS elements
})
babelrc(我包括这个,如果任何导入卡住)
{
"presets":["@babel/preset-env"],
"plugins":[
[
"module-resolver", {
"root": ["./"],
alias : {
"@client": "./client",
"@JSassets": "./server/public",
}
}
]
}
如果你正在使用Vue 3和Composition API(我强烈推荐),并且你经常使用<script>标记,你可以为它写一个“composable”函数:
import { onMounted } from "vue";
export const useScript = (src, async = false, defer = false) => {
onMounted(() => {
// check if script already exists
if (document.querySelector(`head script[src="${src}"`)) return;
// add tag to head
const tag = document.createElement("script");
tag.setAttribute("src", src);
if (async) tag.setAttribute("async", "");
if (defer) tag.setAttribute("defer", "");
tag.setAttribute("type", "text/javascript");
document.head.append(tag);
});
};
或者,如果你正在使用VueUse(我也强烈推荐),你可以使用他们现有的useScriptTag函数。