首页 > 解决方案 > VueJS:不打印方法中返回的数据

问题描述

我成功地将数据输入控制台。当我尝试通过调用双胡须大括号中的方法将该数据打印到页面时,它不会出现在屏幕上。模板中的所有其他数据看起来都很好。

模板:

<template>
   <div>
      <div v-for="data in imageData" :key="data.id">
      <div class="card">
        <img :src="data.source" :alt="data.caption" class="card-img" />
        <div class="text-box">
          <p>{{ moment(data.timestamp.toDate()).format("MMM Do YYYY") }}</p>
          <p>{{ data.caption }}</p>
// The Geocoding method is the problem
          <p>{{reverseGeocode(data.location.df, data.location.wf)}}</p>
        </div>
      </div>
    </div>
  </div>
</template>

方法:

methods: {
    reverseGeocode: (lat, long) => {
      fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=API_KEY&result_type=locality`
          ).then((res) =>
              res.json().then((data) => {
      console.log(data.results[0].formatted_address); // works fine
      return data.results[0].formatted_address;
        })
      );
    },
  },

这是我在道具中获得的图像数据 这是我在道具中获得的图像数据

标签: vue.jsreturn-valuegeocode

解决方案


当您开始在 JavaScript 中发出请求时,您的问题是一个常见问题。

日期请求是异步的,因此在方法执行完成后该方法无法返回值。

想象一下以下调用堆栈:

  1. 启动方法。
  2. 扔取。<- 异步
  3. 完成方法。
  4. 抓取结束。

您正在尝试在第 4 步中返回,它应该在第 3 步中。

要解决这个问题,您应该使用async 和 await。您也可以通过制作组件并传递数据来解决它(这是我最喜欢的,因为您使用的是 vue)。

组件父级

<template>
    <div>
        <component-card v-for="data in imageData" :key="data.id" :dataItem="data">
        </component-card>
    </div>
</template>

子组件

<template>
    <div class="card">
        <img :src="dataItem.source" :alt="dataItem.caption" class="card-img" />
        <div class="text-box">
            <p>{{ moment(dataItem.timestamp.toDate()).format("MMM Do YYYY") }}</p>
            <p>{{ dataItem.caption }}</p>
            <p>{{formattedAddress}}</p>
        </div>
    </div>
</template>
<script>
export default {
    props: {
        dataItem: {
            type: {},
            default: () => ({})
        }
    },
    data() {
        return {
            formattedAddress: ""
        };
    },
    created() {
       this.reverseGeocode(this.dataItem.location.df, dataItem.location.wf) 
    },
    methods: {
        reverseGeocode(lat, long) {
            fetch(
                `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=API_KEY&result_type=locality`
            ).then(res =>
                res.json().then(data => {
                    console.log(data.results[0].formatted_address); // works fine
                    this.formattedAddress = data.results[0].formatted_address;
                })
            );
        }
    }
};
</script>

我还没有尝试过,肯定有些东西丢失了,但模板应该是这样的。


推荐阅读