vue.js - 为什么在使用 axios.post 时我的页面上有一个 OBJECT PROMISE
问题描述
我尝试将 axios post 查询的结果放到 dom 中:
<v-btn fab color="#00C3EA" top right absolute class="white--text">
{{ getRating(tutor) }}
</v-btn>
在我的方法上,我有这个:
async getRating(tutor) {
let rating=0
let lang = ''
if (!this.language) {
lang = this.$route.query.lang
} else {
lang = this.language
}
const rat = await this.$axios.$post('/tutors/getTutorRating.php', '{"tutor_id": '+tutor.id+', "lang": "'+lang+'"}').then((responce)=>{
rating = responce.average_rating
})
console.log(rating)
return rating
},
在控制台日志中我有一个数字结果查询,在页面中我有 [object promise] 我必须做什么才能解决它?
解决方案
编辑:这是一个 axios 发布工作示例的托管代码框:https ://codesandbox.io/s/axios-post-example-jg4yc?file=/src/App.vue
接下来是实际的片段
async testJsonPlaceholder() {
const json = await this.axios.post(
"https://jsonplaceholder.typicode.com/posts",
{
title: "foo",
body: "bar",
userId: 1,
},
{
headers: {
"Content-type": "application/json; charset=UTF-8",
},
}
);
console.log("json", json.data);
return json.data;
},
根据您的 API 正在做什么,这种代码应该可以正常工作。
我还写了一个示例,说明JSONplaceholder的基本帖子如何在testJsonPlaceholder
方法中工作(即使它使用fetch
,也几乎相同,只需删除json()
部分)。
<script>
export default {
methods: {
async getRating(tutor) {
let lang = ''
if (!this.language) {
lang = this.$route.query.lang
} else {
lang = this.language
}
const response = await this.$axios.$post(
'/tutors/getTutorRating.php',
JSON.stringify({ tutor_id: tutor.id, lang }),
)
const result = response.average_rating
console.log("rating's value here", result)
console.log(JSON.parse(JSON.stringify(result)))
return result
},
// the one below is 100% working
async testJsonPlaceholder() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
const json = await response.json()
console.log('json', json)
return json
},
},
}
</script>
我还用 stringify 改变了字符串插值的类型(nvm,axios
显然是自己做的:https ://github.com/axios/axios#request-config ),做同样的事情但更容易阅读。
如果你不想要它,至少使用Template Litterals (es6)有一些容易插值的东西,比如
`this is a simple string, but it's interpolated just here >> ${interpolatedHere} !`
此外,检查您的网络选项卡可以帮助找出问题出在哪里!
推荐阅读
- jenkins - azure devops 中的服务挂钩不会触发 jenkins 作业中的构建
- c# - 如何使用 Visual Studio 2019 和 C# 一次添加所有缺少的使用
- node.js - NodeJS 表子项未定义
- php - vcruntime140.dll 14.0 与 PHP 构建不兼容
- php - WooCommerce:从图库中删除缩略图但保留滑块导航
- python - list.remove(x): x 不在使用 while 循环的列表中
- arrays - 我正在尝试将值写入数组并找到数组的最大值?
- java - 在 MySql Workbench 中插入数据
- javascript - Angular - 观察者地图未按预期工作
- java - 本地化变量的值