Vue3 onMounted中脚本onload函数未执行问题求助
解决Vue3中外部脚本onload不执行及实例获取错误问题
问题根源
- 未挂载脚本到DOM:你创建了script元素,但没有将其添加到页面DOM树(如
<head>或<body>)中,浏览器不会加载未挂载的脚本,导致onload回调永远无法触发。 - 实例获取方式错误:外部脚本加载完成后,其暴露的API会挂载到全局对象(如
ol或neshan)上,而非script元素本身,你通过neshanScript.Map获取实例的写法完全错误。
修正后的代码
<script setup> import { onMounted } from 'vue' function createEl(el, url, type) { const script = document.createElement(el) if (type) script.type = type script.src = url // 给脚本加ID,用于后续判断是否已加载 script.id = 'neshan-ol-sdk' return script } onMounted(() => { // 避免重复加载同一脚本 if (document.getElementById('neshan-ol-sdk')) { initMap() return } const neshanScript = createEl('script', 'https://static.neshan.org/sdk/openlayers/5.3.0/ol.js', 'text/javascript') neshanScript.onload = () => { initMap() } neshanScript.onerror = () => console.error('Neshan SDK加载失败') // 将脚本插入到head中,触发浏览器加载 document.head.appendChild(neshanScript) }) // 提取地图初始化逻辑,方便复用 function initMap() { // 根据Neshan OpenLayers SDK文档,全局对象为ol(若实际是neshan则替换) const map = new ol.Map({ target: 'map', maptype: 'neshan', poi: true, traffic: false }) console.log(map) } </script> <template> <!-- 必须存在对应ID的容器,否则地图无法渲染 --> <div id="map" style="width: 100%; height: 400px;"></div> </template>
额外说明
- 确保模板中存在
id="map"的DOM容器,否则地图初始化会失败。 - 若Neshan SDK实际暴露的全局对象是
neshan而非ol,请将new ol.Map替换为new neshan.Map,具体以官方文档为准。 - 新增的脚本ID判断可避免组件多次挂载时重复发起脚本请求。
内容的提问来源于stack exchange,提问作者hossein samani
相关产品推荐
相关产品推荐

