首页 > 解决方案 > 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]我想知道在承诺解决后如何显示值。

感谢您的帮助

标签: javascriptvue.js

解决方案


您的代码是返回 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;
  }
}

推荐阅读