如何在 VueJs 中的 axios `response` 中访问 `PromiseValue`

Ras*_*san 5 promise laravel vue.js vue-component axios

我正在尝试client在模态中显示信息详细信息。点击后@click="showDetails(props.row.id)"

我正在使用axios.get方法并返回数据。现在,它将数据作为PromiseValue对象返回。如何访问PromiseValue以在 HTML 中显示值。请有人帮我解决问题!我正在尝试如下 -

<button @click="showDetails(props.row.id)"><i class="fas fa-eye"></i></button>
Run Code Online (Sandbox Code Playgroud)

脚本中 -

<script type="text/javascript">
  import axios from 'axios';
  export default {
    data(){
        return{
            leftPanelVisiblity: false,
            singleData: '',            }
    },
    methods:{
        showDetails(id){
            let b = axios.get('/api/clients/'+id)
                      .then(function (response) {
                        return response.data;

                      }).catch(error => {
                            alert(error);
                      });
            //console.log(b);
            this.singleData = b;
            this.leftPanelVisiblity = true
        },
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

最后,我想访问或显示模式中的数据,leftPanelVisiblity例如 -

<p>Name: {{ this.singleData.name }}</p>

或者

<p>Name: {{ this.singleData.email }}</p>.

Geo*_*son 3

使用 Promises 时不能将 Axios 调用分配给变量(除非您使用等待/异步)。

相反,您应该在回调中运行逻辑then。否则,由于 JavaScript 的同步特性,它将在请求完成之前运行。您的代码应该如下所示:

methods:{
  showDetails(id){
    axios.get('/api/clients/'+row.id).then(response => {

      //Logic goes here
      this.singleData = response.data
      this.leftPanelVisibility = true

    }).catch(error => {
      alert(error);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)