ES6类的引用和<Script type=“module“>导致的跨域问题

问题

用ES6的class实现了一个类。并且在script中用一个自执行函数,直接new一个实例来执行。类中方法太多,想重构到别的类中。

然而只要Class 加上import语句,script中就报错,找不到这个类。

解决办法

还是用import引入类。并且在主类下面记得export default 类名

然后设置script属性<script type="module">设置后代码才会被当成ES6模块,才能出现import和export关键词。所以在自执行函数前面 import 主类 from './mainClass.js'这样就能够找到了。

紧接着又报了跨域的错误。vscode可以用LiveServer插件解决这个问题。因为HTML使用type="module"会默认产生跨域请求,而file协议并不支持。

直接右键HTML文件选择Open with Live Server

<template> <div> <!-- 增加加载状态提示 --> <div v-if="loadingStatus === 'loading'">模块加载中...</div> <div v-else> <p v-if="translation">{{ translation }}</p> <button @click="handleTranslate('你好')">执行翻译</button> </div> <p v-if="error" class="error-message">{{ error }}</p> </div> </template> <script> // 模块加载状态枚举 const LOAD_STATES = { IDLE: 'idle', LOADING: 'loading', LOADED: 'loaded', ERROR: 'error' } export default { data() { return { yiyu: null, translation: '', error: null, loadingStatus: LOAD_STATES.IDLE, scriptTag: null // 存储脚本标签引用 } }, mounted() { this.loadExternalScript() }, methods: { // 传统脚本加载方法 loadExternalScript() { this.loadingStatus = LOAD_STATES.LOADING // 创建脚本标签 this.scriptTag = document.createElement('script') this.scriptTag.src = 'https://avatar.gbqr.net/yiyu.js' this.scriptTag.async = true // 成功回调 this.scriptTag.onload = () => { this.loadingStatus = LOAD_STATES.LOADED this.initializeModule() } // 错误处理 this.scriptTag.onerror = (error) => { this.loadingStatus = LOAD_STATES.ERROR this.error = `脚本加载失败: ${error.message || '未知错误'}` this.cleanupScript() } // 添加到DOM document.head.appendChild(this.scriptTag) }, // 模块初始化 initializeModule() { try { // @ts-ignore if (typeof yiyu !== 'undefined') { this.yiyu = yiyu this.yiyu.init({ name: '需要登录的账号', readLocalResource: false }) } else { throw new Error('全局模块对象未定义') } } catch (e) { this.error = `模块初始化失败: ${e.message}` } }, // 执行翻译 async handleTranslate(text) { if (!this.yiyu) { this.error = '翻译引擎未就绪' return } try { this.translation = await this.yiyu.startTranslate(text) } catch (e) { this.error = `翻译错误: ${e.message}` } }, // 清理脚本标签 cleanupScript() { if (this.scriptTag) { document.head.removeChild(this.scriptTag) this.scriptTag = null } } }, beforeDestroy() { // 组件卸载时清理 this.cleanupScript() if (this.yiyu?.cleanup) { this.yiyu.cleanup() } } } </script> <style scoped> .error-message { color: #ff0000; font-weight: bold; } </style>Uncaught SyntaxError: Unexpected token 'export'
04-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值