Component data is loaded asynchronously and other interfaces rely on asynchronous data
- Today I came across a situation where I had a map component
<map />
The parent component asynchronously queries the data and displays it on the map.
Note: get longitude and latitude asynchronously and display on the map
Since both data and maps are asynchronous, it is uncertain which will finish first.
- If the map loads first and the data comes back later, then it works fine
- However, if the data comes back before the map is loaded, an error will be reported.
solution
- After loading the local map, request the interface
In the code
/ / the map component
<div>
<template>
<el-amap vid="container" class="amap"/>
</template>
</div>
<script>
import { lazyAMapApiLoaderInstance } from "vue-amap";
export default {
mounted(){
lazyAMapApiLoaderInstance.load().then(() = >{
// Create a map
this.map = new AMap.Map("container", {
zoom: this.zoom,
center: [116.397428.39.90923].lang: "zh_cn".// Set the map language type
});
// Here, amap API, triggered when the map is finished loading
this.map.on('complete'.function(){
// Map block loading is complete
// Trigger a method to the parent notifying the parent that the map is loaded
this.$emit("mapload")}); }}})</script>
Copy the code
When the child component
is loaded, it will trigger a method mapload (defined by itself) to the parent component. The parent component listens to this method, and then invokes the interface to load data asynchronously. After the data request is returned, it will pass it to < Map /> to complete the output
/ / the parent component
<template>
<div>
<map @mapload="mapload"/>
</div>
</template>
<script>
import map from "./map.vue"
export default {
methods: {mapload(){
// The map has been loaded
//ajax....}}}</script>
Copy the code
Write in the last
Although the code was very simple, I used the map for the first time and was not familiar with the AMap API. I did not know that there was a callback function after the map was loaded, so I started to use setTimeout to finish it reluctantly. And, for the first time, the child has asynchronous data, and the parent relies on the child’s asynchronous data to request the interface. For the record.