VueJS 从 axios 承诺中获取价值

Rah*_*ouk 4 javascript vue.js

我有这个代码

模板 :

<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>
Run Code Online (Sandbox Code Playgroud)

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;
},
Run Code Online (Sandbox Code Playgroud)

问题是console.log显示的值符合预期,但在 Vue 渲染上我得到了这个,[object Promise]我想知道如何在承诺解决后显示值。

感谢您的帮助

bcj*_*ohn 6

您的代码是 return axios ,它是一个承诺对象。如果你想返回最终的持续时间。您应该等待 axios Promise 并返回响应。

async getDuration(id) {
  var duration  = '';
  const response = await axios.post('/api/v1/checkvideo', {
    menu: id
  })
  return response.data[0].datas.duration;
}
Run Code Online (Sandbox Code Playgroud)

编辑

由于async返回了一个 Promise,[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;
  }
}
Run Code Online (Sandbox Code Playgroud)