vue-amap 踩坑之路径规划

1,510 阅读1分钟

情形再现

最近在研究vue-amap的时候,我想要页面加载完成后,就直接路径规划,然后就出现了这个问题:Error in mounted hook: "ReferenceError: AMap is not defined"
image.png
首先一步一步地排除:

解决方法

在项目根目录下.eslintrc.js文件中,查看是否添加以下代码:

module.exports = {
   // 其余代码已省略 ....
    globals: {
        "AMap": 'true',
        "AMapUI": 'true'
    }
}

我添加以上代码后,还是有问题,报错:Error in mounted hook: "ReferenceError: AMap is not defined" 先来看一下我的代码:

<template>
  <div id="home">
    <div class="amap-wrapper">
      <el-amap class="amap-box" :vid="'amap-vue'" :amap-manager="amapManager" :events="mapEvents"></el-amap>
    </div>
  </div>
</template>

<script>
const amapManager = new window.VueAMap.AMapManager();

export default {
  name: 'Home',
  data() {
    return {
      amapManager,
      mapEvents: {
        complete() {}
      }
    };
  },
  mounted() {
    this.getDriving()
  },
  methods: {
    getDriving() {
      const map = this.amapManager.getMap()
      const driving = new AMap.Driving({ map })
      const path = [{keyword: "双流国际机场"}, {keyword: "成都南站"}]
      driving.search(path, function (status, result) {
        console.log(status, "---", result)
      })
    }
  }
};
</script>
<style>
#home { height: 100vh; }
.amap-wrapper { height: 100%; }
</style>

一系列排除下来,发现不能直接在mounted中直接调用getDriving,因为这时候,地图组件还未加载成功。 所以要当地图加载成功后才能进行路径规划,即以下代码:

<template>
  <div id="home">
    <div class="amap-wrapper">
      <el-amap class="amap-box" :vid="'amap-vue'" :amap-manager="amapManager" :events="mapEvents"></el-amap>
    </div>
  </div>
</template>
<script>
const amapManager = new window.VueAMap.AMapManager();

export default {
  name: 'Home',
  data() {
    const that = this
    return {
      amapManager,
      mapEvents: {
        complete() {
        /*
            这个地方要注意this指向的问题,在这里this指向的是AMap这个实力,而并非Vue实例。
            所以要更改this的指向,即:const that = this
        */
          that.getDriving()
        }
      }
    };
  },
  methods: {
    getDriving() {
      const map = this.amapManager.getMap()
      const driving = new AMap.Driving({ map })
      const path = [{keyword: "双流国际机场"}, {keyword: "成都南站"}]
      driving.search(path, function (status, result) {
        console.log(status, "---", result)
      })
    }
  }
};
</script>
<style lang="less">
    #home { height: 100vh; }
    .amap-wrapper { height: 100%; }
</style>

以上就是遇到的这个坑,最重要的就是:这个data()中要注意this指向的问题,在这里this指向的是AMap这个实力,而并非Vue实例。所以要更改this的指向,即:const that = this


Over~