vue.js - 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;
})
);
},
},
解决方案
当您开始在 JavaScript 中发出请求时,您的问题是一个常见问题。
日期请求是异步的,因此在方法执行完成后该方法无法返回值。
想象一下以下调用堆栈:
- 启动方法。
- 扔取。<- 异步
- 完成方法。
- 抓取结束。
您正在尝试在第 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>
我还没有尝试过,肯定有些东西丢失了,但模板应该是这样的。
推荐阅读
- scala - 如何将 Scala Spark Dataframe 转换为 LinkedHashMap[String, String]
- python - Python - 评估条件语句的每个条件
- excel - VBA - 如何从连接中清除连接字符串
- node.js - 使用 Google Cloud KMS 进行 Firebase 实时数据库加密的最佳做法
- c++11 - 有没有办法在模板参数列表中使用 type_traits 来改变类型?
- html - 具有页眉和页脚的外部容器的视差滚动
- asp.net-mvc - 返回与父文件夹和子文件夹中的参数文件名匹配的 MVC 视图
- r - 无法使用 Mac OS 安装 warbleR 包
- mysql - 这个 SQL 查询/连接可能吗?
- java - 组合多个 Single 的最有效方法是什么
- > 成为单曲
- >?