美文网首页
VUE使用axios数据请求时报错 TypeError: Can

VUE使用axios数据请求时报错 TypeError: Can

作者: 最慢的是活着 | 来源:发表于2021-03-29 11:35 被阅读0次

正常情况下在data里面都有做了定义

data() {

    return {

          allPersion:4,

    }

  }

在函数里面进行赋值

this.allPersion =response.data.Data

这时候你运行时会发现,数据可以请求到,但是会报错TypeError: Cannot set property ‘listgroup’ of undefined

主要原因是:

在 then的内部不能使用Vue的实例化的this, 因为在内部 this 没有被绑定。

解决办法:

1、用ES6箭头函数,箭头方法可以和父方法共享变量


GetPatrollerNum(){

          axios({

              method: 'post',

              url: config.api.GetPatrollerNum,

              data:"",

              headers:

                      {

                        'Content-Type': 'application/json'

                      }

            })

            .then((response)=> {

              console.log(response.data.Data);

              this.allPersion=response.data.Data;

            })

          .catch(function (error) {

            console.log(error);

            });

      },

2、在请求axios外面定义一下 var that=this


GetPatrollerNum(){

          var that =this;

        axios({

              method: 'post',

              url: config.api.GetPatrollerOnlineNum,

              data:"",

              headers:

                      {

                        'Content-Type': 'application/json'

                      }

            })

            .then(function (response) {

              console.log(response.data.Data);

              that.allPersion=response.data.Data;

            })

          .catch(function (error) {

            console.log(error);

            }); 

      },```

相关文章

网友评论

      本文标题:VUE使用axios数据请求时报错 TypeError: Can

      本文链接:https://www.haomeiwen.com/subject/hexbhltx.html