【Vue报错】The target environment doesn‘t support dynamic import() syntax so it‘s not possible to use ex
引入外部js(在线js)时Vue报错:The target environment doesn't support dynamic import() syntax so it's not possible to use external
   ·  
 如何在Vue组件中导入在线js代码
比如我们要导入一个在线js:https://unpkg.com/threejs-toys@0.0.8/build/threejs-toys.module.cdn.min.js,我们直接在组件的mounted模块中书写以下代码
    mounted() {
        const s = document.createElement('script');
            s.type = "module";
            s.scr = "https://unpkg.com/threejs-toys@0.0.8/build/threejs-toys.module.cdn.min.js"
            document.body.appendChild(s);
            //console.log(s)
    }
console输出s为<script type="module" src="https://unpkg.com/threejs-toys@0.0.8/build/threejs-toys.module.cdn.min.js"></script>,我们可以在F12下看到<script>标签已经添加到网页中。
如果我们想往<script>标签中添加自定义的代码,可以增加s.innerHTML = "//TODO: your code",考虑到跳转路由后会销毁当前组件,但是网页中<script>标签不会清除。如果后续回到当前组件,<script>又会挂载一次,导致重复<script>,所以在销毁组件时要同时清除<script>标签
<template>
</template>
<script>
export default {
    
    methods: {
        
    },
    mounted() {
        const s = document.createElement('script');
        s.type = 'module';
        s.id = 'jfyy';
        s.innerHTML = "var a = 0\nvar b = 0"
        document.body.appendChild(s);
        console.log(s)
    },
    destroyed() {
        var s = document.getElementById("jfyy")
        s.remove()
    }
}
</script>
<style scoped>
</style>


更多推荐
 


所有评论(0)