javascript - VueJS 从 axios 承诺中获得价值
问题描述
我有这个代码
模板 :
<a href="#" class="video" @click.prevent="checkVideo(subItem.id)" :id="subItem.id" data-toggle="modal" data-target="#playerModal">{{subItem.name}}<span>{{getDuration(subItem.id)}}</span></a>
VueJS 功能:
async getDuration(id) {
var duration = '';
await axios.post('/api/v1/checkvideo', {
menu: id
})
.then(function (response) {
console.log(response.data[0].datas.duration)
return response.data[0].datas.duration;
});
//console.log(duration);
//return duration;
},
问题是console.log
按预期显示值但是在 Vue 渲染上我得到了这个[object Promise]
我想知道在承诺解决后如何显示值。
感谢您的帮助
解决方案
您的代码是返回 axios,它是一个承诺对象。如果要返回最终持续时间。您应该等待 axios 承诺并返回响应。
async getDuration(id) {
var duration = '';
const response = await axios.post('/api/v1/checkvideo', {
menu: id
})
return response.data[0].datas.duration;
}
已编辑
由于async
返回一个承诺,[object Promise] 将始终呈现在屏幕上。如果您想获得特定 ID 的持续时间,我认为这样做是正确的。
data() {
return {
id: null, // Maybe you should store the value of `id` here
duration: null
}
},
mounted() {
this.getDuration(this.id)
},
methods: {
async getDuration(id) {
var duration = '';
const response = await axios.post('/api/v1/checkvideo', {
menu: id
})
this.duration = response.data[0].datas.duration;
}
}
推荐阅读
- python - Tkinter 全局变量/.get()
- javascript - 有没有办法通过firebase google auth获取用户位置信息?
- mongodb - MongoDB对多个字段的聚合查询
- pandas - 如何在主列下创建子列
- python - 带有参数的 Pyodbc SQL Server 存储过程在本地机器上工作,但在服务器上不工作
- scala - 有一个旧库没有为 scala 2.13.x 构建,如何创建本地 maven 存储库查找?
- amazon-web-services - 在 Amazon Redshift 创建表语句中动态添加位置
- java - 如何在不将字符转换为 Java 中的转义 unicode 字符的情况下保存 UTF-8 文件?
- amazon-web-services - 使用运行命令从 s3 下载脚本文件夹
- sql - SQL JSON 嵌套选择