vue给data中的数据赋值报错问题(TypeError: Cannot set property ‘tableData‘ of undefined)

问题背景

最近刚入门vue,有个典型的场景,也是简单的坑。就是需要通过axios请求数据之后,将数据赋予到data中的tableData,而table组件会根据tableData双向绑定自动渲染。

但是当我赋值的时候TypeError: Cannot set property 'tableData' of undefined。究竟怎么回事呢。

分析

代码看起来,好像并没有什么毛病。。。

export default {
  data() {
    return {
      total: 0, //默认数据总数
      searchParam:{
        limit: 10, //每页的数据条数
        page: 1, //默认开始页面
        certNumber: "",
        certLevel: "",
        certCompanyName: "",
      },
      tableData: []
    };
  },
onSearch: function(){
      axios.post('/api/certCompany/list2',JSON.stringify(this.searchParam))
      .then(function (response) {
        console.log(response);
        this.tableData=response.data.data;
        this.total=response.data.count;
      })
      .catch(function (error) {
        console.log(error);
      });
    }
};

然而问题是出来了this.tableData因为用了 function 函数 的原因,在函数里面,this是指向函数本身,已经不是外部的默认this

解决方案

使用一个 that 指向 外部的this ,然后调用 that.tableData ,轻松搞定。

onSearch: function(){
      const that=this; //用that解决函数内部this指向问题 zhengkai.blog.csdn.net
      axios.post('/api/certCompany/list2',JSON.stringify(this.searchParam))
      .then(function (response) {
        console.log(response);
        that.tableData=response.data.data;
        that.total=response.data.count;
      })
      .catch(function (error) {
        console.log(error);
      });
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/moshowgame/article/details/107286506