zoukankan      html  css  js  c++  java
  • VUE使用axios数据请求时报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法

    正常定义全局变量:

    data:function (){
          return{
            currentOrders:[]
          }
        },
    

      使用Axios发送请求并获取后端数据时,如果在then中使用this.currentOrders会出现TypeError: Cannot set property 'xxxx' of undefined错误。

      原因是使用this$axios().then(function(response){}).catch()格式获取参数,then的内部 this 没有被绑定,所以不能使用Vue的实例化的this。

      解决办法一:在this.$axios外部将this赋值为自定义变量:var that = this,然后在then里面使用that.currentOrders

    var that = this
          this.$axios({
            method: 'get',
            url: 'xxxxxx',
          }).then(function (response) {
            var jsonObj = JSON.parse(JSON.stringify(response.data))
            if (jsonObj.code === ERR_ok){
              that.currentOrders = jsonObj.data
            }
          }).catch(function (error) {
            console.log(error);
          })

    第二种方法:用ES6箭头函数,箭头方法可以和父方法共享变量

    this.$axios({
            method: 'get',
            url: 'xxxxxx',
          }).then((response)=>{})
          .catch(){}
     
    

      

  • 相关阅读:
    auto_ptr智能指针
    友元函数
    设计模式之单件模式
    vs2008工程部署不成功,可能是远程文件路径出现问题
    printf(“%06d ”,x);
    16进制到文本字符串的转换,在线实时转换
    文件包含
    pwn-200
    misc-3-1
    misc-适合作为桌面
  • 原文地址:https://www.cnblogs.com/xjtsh/p/12887829.html
Copyright © 2011-2022 走看看