
在之前 HTML + JS 的开发中,直接使用 script 标签引入百度地图 API 和外部库是常规做法。然而,在 Vue3.0 环境下,情况略有不同。
异步加载百度地图 API
为了优化资源加载,Vue3.0 推荐使用异步加载方式。在 index.html 中引入百度地图 API 脚本:
加载完百度地图 API 后,可以将其标记为全局变量:
立即学习“前端免费学习笔记(深入)”;
declare global {
interface Window {
BMap: any;
}
}引入外部库
在加载百度地图 API 后,我们可以按照顺序引入其他外部库,如 TrafficControl.js 和 LuShu.js:
const insertScript = (src: string) => {
const script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', src);
script.setAttribute('async', 'false');
document.head.insertBefore(script, document.head.firstChild);
};
window.BMap.addEventListener('load', () => {
insertScript('path/to/TrafficControl.js');
insertScript('path/to/LuShu.js');
});自定义方法
如果在 HTML 项目中使用了自定义方法,在 Vue3.0 中需要对这些方法进行修改。例如,将它们封装到 Vue 组件或使用 ESM 模块的形式导出:
// Vue 组件
export default defineComponent({
setup() {
return {
customMethod() {
// 自定义方法实现
},
};
},
});
// ESM 模块
const myModule = {
customMethod() {
// 自定义方法实现
},
};
export default myModule;在 Vue 组件或 ESM 模块中调用这些方法时,不需要再使用全局变量 BMap,如下:
this.customMethod(); // Vue 组件 myModule.customMethod(); // ESM 模块











