A rerun

I’ve been working onvue-amapWhen I wanted the page to finish loading, I went straight to path planning, and then this problem appeared:Error in mounted hook: "ReferenceError: AMap is not defined"



First eliminate step by step:

The solution

In the.eslintrc.js file in the project root directory, see if you can add the following code:

module.exports = {
   // The rest of the code has been omitted....
    globals: {
        "AMap": 'true'."AMapUI": 'true'}}Copy the code

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: "Shuangliu International Airport"}, {keyword: Chengdu South Railway Station}]
      driving.search(path, function (status, result) {
        console.log(status, "-", result)
      })
    }
  }
};
</script>
<style>
#home { height: 100vh; }
.amap-wrapper { height: 100%; }
</style>
Copy the code

In Mounted, you cannot call getDriving directly because the map component has not been loaded successfully. Therefore, path planning can only be carried out after the local map is loaded successfully, that is, the following code:

<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: "Shuangliu International Airport"}, {keyword: Chengdu South Railway Station}]
      driving.search(path, function (status, result) {
        console.log(status, "-", result)
      })
    }
  }
};
</script>
<style lang="less">
    #home { height: 100vh; }
    .amap-wrapper { height: 100%; }
</style>
Copy the code

The most important thing to note in this data() is that this refers to the AMap capability, not the Vue instance. So change the pointer to this, const that = this


Over~