调用组件时的竞争条件

我有 2 个组件正在加载到“应用程序”中,第一个组件通过进行 2 个 axios.get 调用将外部 IP 地址解析为地理地址,然后将它们(通过发射)返回给 App.vue。


然后我调用“天气”来解析从前 2 次调用到由 darksky API 返回的那个 lat/long 的一些 json 的 lat/long。有时(50-60% 的时间)我遇到了一个竞争条件,我将 0/0 发送到天气(这是我在 App.vue 中初始化 lat/long 的内容)并且不知道如何解决它。我希望以下代码能够更可靠地运行。


应用程序.vue


<template>

  <div id="app">

        <img alt="Vue logo" src="./assets/logo.png">

    <ip @response="onResponse" /> //Needs to finish before next line runs (has axios calls)

    <Weather msg="The weather for:" :lat="lat" :long="long" :ip="ip" :city="city" :country="country"/>

  </div>

</template>


<script>

import Weather from './components/Weather.vue'

import ip from './components/ip_resolve.vue'


export default {

  name: 'App',

  data() {

    return {

      lat: 0,

      long: 0,

      ip: 0,

      country: 0,

      city: 0 

    }

  },

  components: {

    Weather,

    ip

  },


  //Accepts emitted values from ip_resolve -- needs to change values in data before Weather runs

  methods: {

    onResponse(event) {

      this.lat = event.lat

      this.long = event.long

      this.ip = event.ip

      this.country = event.country

      this.city = event.city

    }

  }

}

</script>


慕田峪7331174
浏览 125回答 1
1回答

呼如林

通常,您会使用 vuex 之类的东西将此模型逻辑分离到自己的模块中,因此组件的数据流是完全单向的。但在这种情况下,最简单的解决方案是在 App.vuev-if="responseReady"中向组件添加指令,<Weather>以便在数据准备好之前它不会被挂载。您还需要为这个新道具添加一个布尔标志到dataand onResponse。同样,这是快速而肮脏的解决方案。&nbsp; <Weather v-if="responseReady"&nbsp; msg="The weather for:" :lat="lat" :long="long" :ip="ip" :city="city" :country="country"/>...&nbsp; data() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; lat: 0,&nbsp; &nbsp; &nbsp; &nbsp; long: 0,&nbsp; &nbsp; &nbsp; &nbsp; ip: 0,&nbsp; &nbsp; &nbsp; &nbsp; country: 0,&nbsp; &nbsp; &nbsp; &nbsp; city: 0,&nbsp; &nbsp; &nbsp; &nbsp; responseReady: false&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp;...&nbsp; &nbsp; onResponse(event) {&nbsp; &nbsp; &nbsp; this.lat = event.lat&nbsp; &nbsp; &nbsp; this.long = event.long&nbsp; &nbsp; &nbsp; this.ip = event.ip&nbsp; &nbsp; &nbsp; this.country = event.country&nbsp; &nbsp; &nbsp; this.city = event.city&nbsp; &nbsp; &nbsp; this.responseReady = true;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript