【问题标题】:How to access `PromiseValue` in axios `response` in VueJs如何在 VueJs 中的 axios `response` 中访问 `PromiseValue`
【发布时间】:2019-10-10 04:26:36
【问题描述】:

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

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

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

而在脚本-

<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>

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

&lt;p&gt;Name: {{ this.singleData.name }}&lt;/p&gt;

或者

&lt;p&gt;Name: {{ this.singleData.email }}&lt;/p&gt;.

【问题讨论】:

    标签: laravel vue.js promise axios vue-component


    【解决方案1】:

    在使用 Promises 时,您不能将 Axios 调用分配给变量(除非您使用的是 await/async)。

    相反,您应该在 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);
        });
      }
    }
    

    【讨论】:

    • showDetails(id){ axios.get('/api/clients/'+id) .then(function (response) { let b = response.data; this.singleData = b; this.leftPanelVisiblity = true }).catch(error =&gt; { alert(error); }); }, .... 但收到此错误 -TypeError: Cannot set property 'singleData' of undefined
    • @RashedHasan 我已经更新了我的回复。它现在使用短箭头函数到this 范围内不会在回调中改变。
    【解决方案2】:

    你需要为你的 axios 的响应分配一个变量:

     showDetails(id){
            axios.get('/api/clients/'+id)
                      .then(function (response) {
                          this.singleData = response.data;
                      }).catch(error => {
                            alert(error);
                      });
            console.log(this.sigleData);
    
            this.leftPanelVisiblity = true
        },
    

    【讨论】:

    • 出现TypeError: Cannot set property 'singleData' of undefined 错误。
    猜你喜欢
    • 2018-09-13
    • 2020-07-04
    • 2021-02-13
    • 1970-01-01
    • 2017-11-26
    • 2014-11-18
    • 2020-08-14
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多